Commit 91cc3614 authored by Konstantinos Agiannis's avatar Konstantinos Agiannis

add junior codes from rontogiannis

parent ef410cd7
#include <stdio.h>
#include <algorithm>
using namespace std;
const int MAXN = 100005;
int stalls[MAXN];
bool check_d(int N, int C, int d) {
int remaining_cows = C;
int current_stall = 0;
int previous_stall = -1;
while(remaining_cows > 0 && current_stall < N) {
if(previous_stall == -1) {
remaining_cows--;
previous_stall = current_stall;
current_stall++;
}
else {
if(stalls[current_stall] - stalls[previous_stall] >= d) {
remaining_cows--; // place a cow on current_stall
previous_stall = current_stall;
current_stall++;
} else {
current_stall++; // cannot add cow; move to next stall
}
}
}
if(remaining_cows == 0) return true;
else return false;
}
int main() {
int T;
scanf("%d", &T);
while(T--) {
int N, C;
scanf("%d %d", &N, &C);
for(int i=0; i<N; ++i)
scanf("%d", stalls+i);
sort(stalls, stalls+N);
int lo = 0, hi = stalls[N-1]-stalls[0], result = 0;
while(lo <= hi) {
int mid = (lo+hi)/2;
if(check_d(N, C, mid) == true) {
lo = mid+1;
result = mid;
}
else hi = mid - 1;
}
printf("%d\n", result);
}
return 0;
}
\ No newline at end of file
#include <stdio.h>
const int MAXN = 100005;
int A[MAXN+1];
int bsearch(int lo, int hi, int key) {
if(lo == hi) {
if(A[lo] == key) return lo;
else return -1;
}
int mid = (lo+hi)/2;
if(A[mid] < key) {
lo = mid+1;
return bsearch(lo, hi, key);
}
else if(A[mid] > key) {
hi = mid-1;
return bsearch(lo, hi, key);
}
else return mid;
}
int bsearch_iterative(int N, int key) {
int lo = 0, hi = N-1;
while(lo < hi) {
int mid = (lo+hi)/2;
if(A[mid] < key) lo = mid+1; // continue on the right half
else if(A[mid] > key) hi = mid-1; // continue on the left half
else return mid;
}
if(A[lo] == key) return lo;
else return -1;
}
int main() {
int N, key;
scanf("%d %d", &N, &key);
for(int i=0; i<N; ++i) {
scanf("%d", A+i);
}
printf("%d\n", bsearch(0, N-1, key));
printf("%d\n", bsearch_iterative(N, key));
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment