1.链接地址:
http://bailian.openjudge.cn/practice/1723/
http://poj.org/problem?id=1723
2.题目:
- 总时间限制:
- 1000ms
- 内存限制:
- 65536kB
- 描述
- 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.- 输出
- 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.- 样例输入
5
1 2
2 2
1 3
3 -2
3 3- 样例输出
8- 来源
- CEOI 1998
3.思路:
4.代码:
//1723_01.cpp
//2010-04-09 by wuzhihui #include<iostream>
#include<cstdio>
#include <cmath> using namespace std;
int x[],y[],c[]; //快速排序
int Partition(int a[],int low,int high)
{
int temp=a[low];
while(low<high)
{
while(low<high&&a[high]>=temp) high--;
a[low]=a[high];
while(low<high&&a[low]<=temp) low++;
a[high]=a[low];
}
a[low]=temp;
return low;
}
void QSort(int a[],int low ,int high)
{
int pivotloc;
if(low<high)
{
pivotloc=Partition(a,low,high);
QSort(a,low,pivotloc-);
QSort(a,pivotloc+,high);
}
}
void QuickSort(int a[],int size)
{
QSort(a,,size-);
} long long f(int x[],int y[],int size)
{
int i;
QuickSort(x,size);
for(i=;i<size;i++)
{
c[i]=x[i]-i;
}
QuickSort(y,size);
QuickSort(c,size);
long long count=;
for(i=;i<size;i++)
{
count+=abs(y[i]-y[size/])+abs(x[i]-(c[size/]+i));
}
return count;
}
int main()
{
//测试快排的正确性
/*int test[10]={9,8,7,6,5,4,3,2,1,0};
int testSize=10;
QuickSort(test,testSize);
for(int i=0;i<10;i++) {cout<<test[i]<<" ";}
cout<<endl; */ int size;
int i,j;
long long count;
while((cin>>size)&&size!=)
{
for(i=;i<size;i++)
{
cin>>x[i]>>y[i];
} //测试输入是否正确
/*for(i=0;i<size;i++)
{
cout<<x[i]<<" "<<y[i];
cout<<endl;
} */ count=f(x,y,size);
printf("%lld\n",count);
} //system("pause");
return ;
}