SOLDIERS
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
5
1 2
2 2
1 3
3 -2
3 3
Sample Output
8
分析:
纵向横向可以分开来考虑。合理猜想当都移到中位数那一横排的时候纵向上移动的步数最少,很容易证明。
接下来考虑横向连续排列的问题,首先排序。接着枚举的方式很容易想到,会不会超时我不知道= =。
假设起点为index,则横向总步数为x[i]-(a+i)的绝对值总和。可以证明仍是中位数的时候步数最少。
code:
#include<iostream>
#include<cstdlib>
#include<cmath>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int x[10005];
int y[10005];
int main()
{
int i,j,n,step=0,mid;
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d %d",&x[i],&y[i]);
sort(x,x+n);
sort(y,y+n);
for(i=0;i<n;i++)
x[i]-=i;
sort(x,x+n);
mid=(n+1)/2-1;
for(i=0;i<n;i++)
step+=abs(y[i]-y[mid])+abs(x[i]-x[mid]);
printf("%d\n",step);
return 0;
}