#include <string.h>
#include <limits.h>
+static inline int distance(int crabs[], int ncrabs, int pos)
+{
+ int dist = 0;
+ for (int i = 0; i<ncrabs; i++)
+ dist += abs(crabs[i]-pos);
+ return dist;
+}
+
int main()
{
char *buf = NULL;
ncrabs++;
}
- int mindist = INT_MAX;
- for (int i = minp; i<=maxp; i++) {
- int dist = 0;
- for (int j = 0; j<ncrabs; j++)
- dist += abs(crabs[j]-i);
- if (dist < mindist)
- mindist = dist;
+ int middledist = INT_MAX;
+ int middle = (maxp+minp)/2;
+ while (middle != maxp && middle != minp) {
+ middledist = distance(crabs, ncrabs, middle);
+ if (distance(crabs, ncrabs, middle+1) > middledist) {
+ maxp = middle;
+ middle = (middle+minp)/2;
+ } else {
+ minp = middle;
+ middle = (middle+maxp)/2;
+ }
}
- printf("%d\n", mindist);
+ printf("%d\n", middledist);
}
#include <string.h>
#include <limits.h>
+static inline int distance(int crabs[], int ncrabs, int pos)
+{
+ int dist = 0;
+ for (int i = 0; i<ncrabs; i++) {
+ int d = abs(crabs[i]-pos);
+ dist += (d*d+d)/2;
+ }
+ return dist;
+}
+
int main()
{
char *buf = NULL;
ncrabs++;
}
- int lastdist = INT_MAX;
- int dist = INT_MAX;
- int i = minp;
- do {
- lastdist = dist;
- dist = 0;
- for (int j = 0; j<ncrabs; j++) {
- int d = abs(crabs[j]-i);
- for (int k = 1; k<=d; k++)
- dist += k;
+ int middledist = INT_MAX;
+ int middle = (maxp+minp)/2;
+ while (middle != maxp && middle != minp) {
+ middledist = distance(crabs, ncrabs, middle);
+ if (distance(crabs, ncrabs, middle+1) > middledist) {
+ maxp = middle;
+ middle = (middle+minp)/2;
+ } else {
+ minp = middle;
+ middle = (middle+maxp)/2;
}
- i++;
- } while (dist < lastdist);
- printf("%d\n", lastdist);
+ }
+ printf("%d\n", middledist);
}