Soldiers
N soldiers of the land Gridland are randomly scattered around the country. A position in Gridland is given by a pair (x, y) of integer coordinates. Soldiers can move - in one move, one soldier can go one unit up, down, left or right (hence, he can change either his x or his y coordinate by 1 or -1).
The soldiers want to get into a horizontal line next to each other (so that their final positions are (x, y), (x+1,y), ..., (x+N-1, y), for some x and y). Integers x and y, as well as the final order of soldiers along the horizontal line is arbitrary.
The goal is to minimise the total number of moves of all the soldiers that takes them into such configuration.
Two or more soldiers must never occupy the same position at the same time.
Input
The first line of the input contains the integer N, 1 <= N <= 10000, the number of soldiers.
The following N lines of the input contain initial positions of the soldiers : for each i, 1 <= i <= N, the (i+1)st line of the input file contains a pair of integers x[i] and y[i] separated by a single blank character, representing the coordinates of the ith soldier, -10000 <= x[i],y[i] <= 10000.
Onput
The first and the only line of the output should contain the minimum total number of moves that takes the soldiers into a horizontal line next to each other.
Sample Input Sample Output
5 8
1 2
2 2
1 3
3 -2
3 3
大致意思:有n个士兵分别在n个坐标处,每次只能有一个士兵移动且每次只能移动一个坐标,最后所有士兵移动到统一y坐标,x坐标按顺序排列,并输出最终的最小移动步数。(x与y坐标任意)
解题思路:
首先所有的士兵需要移动到统一y坐标,那么就需要找到所有y坐标的中间值mid,然后计算所有y坐标到中间值mid的绝对值之和,这就是所有士兵到y坐标需要移动的次数
然后是对x坐标的处理,最后所有的x坐标需要排列成k,k+1,k+2,k+3,...,k+n。所以可以使x[i]-i之后看做是移动到同一个x坐标,这样就可以把问题简化成y坐标的处理方法。
代码如下:
#include<stdio.h>
#include<math.h>
void Swap(int a[],int i,int j)//交换i和j的值
{
int temp=a[i];
a[i]=a[j];
a[j]=temp;
}
void QuickSort(int a[],int left,int right)//快排序
{
if(left>right)
return;
int pivot=a[right];
int p=left;
for(int i=left;i<right;i++)
if(a[i]<pivot)
Swap(a,i,p++);
Swap(a,right,p);
QuickSort(a,left,p-1);
QuickSort(a,p+1,right);
}
int qiujie(int a[],int n)//求解x和y坐标的最小移动步数之和
{
QuickSort(a,0,n-1);//xianjin先进行快排序
int sum=0,mid=n/2;//取中间值
for(int i=0;i<n;i++)
sum+=abs(a[i]-a[mid]);//求所有x和y坐标到中间值的绝对值
return sum;
}
int main()
{
int n;
scanf("%d",&n);
int x[n],y[n],z[n];
for(int i=0;i<n;i++)
scanf("%d %d",&x[i],&y[i]);
QuickSort(x,0,n-1);
for(int i=0;i<n;i++)
z[i]=x[i]-i;//对x坐标的简化处理
printf("%d",qiujie(y,n)+qiujie(z,n));
return 0;
}