POJ-1723

来源:互联网 发布:图像算法工程起薪 编辑:程序博客网 时间:2024/06/05 11:25

题目:

SOLDIERS
Time Limit: 1000MS Memory Limit: 10000KTotal Submissions: 9225 Accepted: 3215

Description

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. 

Output

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

51 22 21 33 -23 3

Sample Output

8

Source

CEOI 1998
个人理解:

/*题目:有N个士兵,每个士兵站的位置用一个坐标(x,y)表示,现在要将N个士兵站在同一个水平线,即所有士兵的y坐标相同并且x坐标相邻,每个士兵每次可以移动一个位置。求出最少的移动步数。解题思路:Y轴方向上的考虑设目标坐标为M,即n个士兵最终需要移动到的Y轴的坐标值为M当M=SUM(Y0+Y1+……+Yn-1)/n时  即M为中位数时坐标点M 的左右两侧士兵个数一样对于两个士兵 无论哪个士兵走 只要是两个士兵之间的位置用的步数是一样的中位数保证了M俩没那个册的士兵成对存在所以 M取中间点的值使得S为最少(最优)处于中间位置的士兵的Y轴坐标值就是“最终位置”的Y轴坐标X轴方向上的考虑如果最中间的人集合地点x值m,那么他左边的人的集合地点是m-1,右边的人的集合地点是m+1……为了方便计算,我把左边的人横坐标值+1,右边的人横坐标-1,两人等价集合到m点。以此类推,处理完整个数组,问题又变成把所以的人集合到一点。所以只要把新数组排个序,求中位数即可。*/
AC情况:


代码:

#include<stdio.h># include <math.h># define N 10000void change(int *a,int *b){//交换函数 交换a b的值   int c=*a;   *a=*b;   *b=c;}void Qsort(int A[],int left,int right);//快速排序<降序>int X[N],Y[N],n,i,sum,j,midX,midY;int main(){    //freopen("AAA.txt","r",stdin);    scanf("%d",&n);    for(i=0;i<n;i++)       scanf("%d %d",&X[i],&Y[i]);    Qsort(X,0,n-1);    Qsort(Y,0,n-1);    midY=Y[(n+1)/2-1];    for(i=0;i<n;i++)X[i]-=i;    Qsort(X,0,n-1);    midX=X[(n+1)/2-1];    for(i=0;i<n;i++)    sum+=fabs(Y[i]-midY)+fabs(X[i]-midX);    printf("%d\n",sum);    return 0;}void Qsort(int A[],int left,int right)//快速排序 升序{    int i=left,j=right,temp=A[left];    if(left>=right)  return;    while(i!=j)    {        while(A[j]>=temp && i<j) j--;        while(A[i]<=temp && i<j)i++;        if(i<j)            change(&A[i],&A[j]);     }    if(i!=left)change(&A[left],&A[i]);    Qsort(A,left,i-1);    Qsort(A,i+1,right);}


原创粉丝点击