eleven

来源:互联网 发布:知乎 金庸 编辑:程序博客网 时间:2024/06/08 10:52
题目: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. 

输入: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. 

输出:
样例输出:8

个人理解:首先移向中位数肯定是最好的选择,纵坐标的移动肯定是各个纵坐标减纵坐标中位数的绝对值的和,而横坐标的移动是a[i]-i减其中位数的和,相加即可。

代码:#include <iostream>#include <algorithm>#include <cstring>#include <cstdio>using namespace std;int x[10001];int y[10001];int z[10001];int main(){int N;   scanf("%d", &N);    memset(x,0,sizeof(x));    memset(y,0,sizeof(x));    memset(z,0,sizeof(x));    for (int i = 0; i < N; i++)    {        scanf("%d%d", &x[i], &y[i]);    }    sort(x,x+N);    sort(y, y + N);    for (int i = 0; i < N; i++)    {        z[i] = x[i] - i;    }    sort(z, z+N);    int a=z[N/2],b=y[N/2],res=0;    for (int i=0;i <N;i++)    {        res += abs(z[i]-a);        res += abs(y[i]-b);    }        printf("%d",res);      return 0;}