POJ1723.SOLDIERS 排序+思维

1.题目描述:

SOLDIERS
Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 8490 Accepted: 2993

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

2.题意概述:

有N个士兵,每个士兵站的位置用一个坐标(x,y)表示,现在要将N个士兵站在同一个水平线,即所有士兵的y坐标相同并且x坐标相邻,每个士兵每次可以移动一个位置。求出最少的移动步数。


3.思路分析:

对x方向和y方向分开讨论。
1  y方向:
要使士兵最后位于同一水平线,则最终所有士兵的y坐标相同。
将所有坐标的y值从小到大排序,对于首尾两个y值,移动到它们之间的任何y值所需要的步数是相同的,所以 最终的y值取中位数。
y方向的步数y_steps=|y[0]-y_mid|+|y[1]-y_mid|+...+|y[n-1]-y_mid|,y_mid=y[n/2]。
2  x方向:
x方向稍微复杂点,先对所有x坐标从小到大排序,由于要移动步数最少,所以最终的x坐标相对位置与排序后的x坐标相对位置相同。


4.AC代码:

#include <iostream>
#include <cstdlib>
#define maxn 10004
using namespace std;
int a[maxn], b[maxn];

int cmp(const void *a, const void *b)
{
	return *(int*)a - *(int*)b;
}
int main()
{
	int test, mid_a, mid_b, ans = 0;
	cin >> test;
	for (int i = 0; i < test; i++)
		cin >> a[i] >> b[i];
	qsort(a, test, sizeof(a[0]), cmp);
	qsort(b, test, sizeof(b[0]), cmp);
	for (int j = 0; j < test; j++)
		a[j] -= j;
	qsort(a, test, sizeof(a[0]), cmp);
	mid_a = a[test / 2];
	mid_b = b[test / 2];
	for (int k = 0; k < test; k++)
		ans += abs(a[k] - mid_a) + abs(b[k] - mid_b);
	cout << ans << endl;
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值