士兵战队问题
首先X方向和Y方向可以分开计算,Y方向上,所有点到所求点的距离差的绝对值最小,将所有士兵的y值排序,求中位数,即所求y0.
x方向上经过转化也可变为求中位数。
#include<stdio.h>
int rx[10000];
int ry[10000];
void qsort(int *r,int low ,int high);
int partition(int *r,int low,int high);
int main()
{
int n,i;
int step=0;
int x_median;
int y_median;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&rx[i]);
scanf("%d",&ry[i]);
}
qsort(ry,0,n-1);
y_median=ry[n/2];
for(i=0;i<n;i++)
{
if(ry[i]-y_median>=0)
step+=(ry[i]-y_median);
else
step-=(ry[i]-y_median);
}
qsort(rx,0,n-1);
for(i=0;i<n;i++)
{
rx[i]-=i;
}
qsort(rx,0,n-1);
x_median=rx[n/2];
for(i=0;i<n;i++)
{
if(rx[i]-x_median>=0)
step+=(rx[i]-x_median);
else
step-=(rx[i]-x_median);
}
printf("%d\n",step);
}
void qsort(int *r,int low ,int high)
{
int pivot;
if(low<high)
{
pivot=partition(r,low,high);
qsort(r,low,pivot-1);
qsort(r,pivot+1,high);
}
}
int partition(int *r,int low,int high)
{
int pivot_num=r[low];
while(low<high)
{
while(r[high]>=pivot_num&&low<high)
high--;
r[low]=r[high];
while(r[low]<=pivot_num&&low<high)
low++;
r[high]=r[low];
}
r[low]=pivot_num;
return low;
}