SOLDIERS 货仓选址

5 篇文章 0 订阅

SOLDIERS
Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 12995 Accepted: 4321

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

Source
CEOI 1998

首先一个序列中 所有数到中位数的距离和是最短的 这样先找出y 的中位数算出士兵在y 方向移动的步数
先对x进行一次sort 得到 x的递增序列
因为最后x 是相邻着 的 即x[1]=a,x[2]=a+1…

abs(a+i-1-x[i])也就是这个点移动要相应点的距离
设一个数组x[i]-i+1 那么易得a为这个数组的中位数时是距离最近的。

#include<algorithm>
#include<cstdio>
using namespace std;
const int N=10010; int x[N],y[N];
typedef long long ll;
int main()
{
	int n;
	scanf("%d",&n);
	for(int i=1;i<=n;i++) {
	scanf("%d%d",&x[i],&y[i]);	
	}
	sort(x+1,x+1+n);
	for(int i=1;i<=n;i++) x[i]-=i-1;
	sort(x+1,x+1+n);
	sort(y+1,y+1+n);
	int xx=x[(n+1)/2];
	int yy=y[(n+1)/2];ll ans=0;
	for(int i=1;i<=n;i++)
	{
		ans+=labs(x[i]-xx)+labs(y[i]-yy);
	}
	printf("%lld\n",ans);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值