士兵站队算法

来源:百度知道 编辑:UC知道 时间:2024/06/16 01:28:31
这是北大ACM网上的一道题,编号":1723
士兵站队问题
«问题描述:
在一个划分成网格的操场上,n个士兵散乱地站在网格点上。网格点由整数坐标(x,y)表示。士兵们可以沿网格边上、下、左、右移动一步,但在同一时刻任一网格点上只能有一名士兵。按照军官的命令,士兵们要整齐地列成一个水平队列,即排列成(x,y),(x+1,y),…,(x+n-1,y)。如何选择x和y的值才能使士兵们以最少的总移动步数排成一列。
以下是我的算法:自己估计是X的站头确定方法有问题...希望大牛们可以指点一下...

#include <iostream>
#include <algorithm>

using namespace std;

int x[10000];
int y[10000];

int main()
{
int n;
cin>>n;

for(int i = 0; i < n; ++i)
cin>>x[i]>>y[i];

int tempx;
int tempy;

nth_element(y, y + n / 2, y + n);
tempy = y[n/2];

sort(x, x + n);
for(int i = 0; i < n; ++i)
x[i] -= i;

nth_element(x, x + n / 2, x + n);
tempx= x[n/2];

int total=0;

for(int i = 0; i < n; ++i)
{
total += abs(y[i] - tempy);
total += abs(x[i] - tempx);
}
cout<<total<<endl;

}

好题啊