We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
int cmpfunc(const void *a, const void b) {
return ((int*)a - (int)b);
}
int lower_bound(int *arr, int n, int val) {
int l = 0, r = n;
while (l < r) {
int mid = (l + r) / 2;
if (arr[mid] < val) l = mid + 1;
else r = mid;
}
return l;
}
void printMedian(int *arr, int n) {
if (n == 0) {
printf("Wrong!\n");
return;
}
if (n % 2 == 1) {
printf("%d\n", arr[n/2]);
} else {
long long sum = (long long)arr[n/2 - 1] + (long long)arr[n/2];
if (sum % 2 == 0) printf("%lld\n", sum/2);
else printf("%.1f\n", sum/2.0);
}
}
void median(int N, char (*s)[3], int *x) {
int *arr = malloc(N * sizeof(int));
int size = 0;
for (int i = 0; i < N; i++) {
if (s[i][0] == 'a') {
int pos = lower_bound(arr, size, x[i]);
for (int j = size; j > pos; j--) arr[j] = arr[j-1];
arr[pos] = x[i];
size++;
printMedian(arr, size);
} else {
if (size == 0) {
printf("Wrong!\n");
continue;
}
int pos = lower_bound(arr, size, x[i]);
if (pos == size || arr[pos] != x[i]) {
printf("Wrong!\n");
continue;
}
for (int j = pos; j < size-1; j++) arr[j] = arr[j+1];
size--;
printMedian(arr, size);
}
}
free(arr);
}
int main() {
int N;
scanf("%d", &N);
char s[N][3];
int x[N];
for (int i = 0; i < N; i++) {
scanf("%s %d", s[i], &x[i]);
}
median(N, s, x);
return 0;
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Median Updates
You are viewing a single comment's thread. Return to all comments →
solution of this problem in C language
include
include
int cmpfunc(const void *a, const void b) { return ((int*)a - (int)b); }
int lower_bound(int *arr, int n, int val) { int l = 0, r = n; while (l < r) { int mid = (l + r) / 2; if (arr[mid] < val) l = mid + 1; else r = mid; } return l; }
void printMedian(int *arr, int n) { if (n == 0) { printf("Wrong!\n"); return; } if (n % 2 == 1) { printf("%d\n", arr[n/2]); } else { long long sum = (long long)arr[n/2 - 1] + (long long)arr[n/2]; if (sum % 2 == 0) printf("%lld\n", sum/2); else printf("%.1f\n", sum/2.0); } }
void median(int N, char (*s)[3], int *x) { int *arr = malloc(N * sizeof(int)); int size = 0;
}
int main() { int N; scanf("%d", &N); char s[N][3]; int x[N]; for (int i = 0; i < N; i++) { scanf("%s %d", s[i], &x[i]); } median(N, s, x); return 0; }