SOLDIERS(poj1723 排序/中位数/货舱选址问题扩展)

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
题意

有N个士兵随机的分布在坐标轴上,现在要我们通过左右上下的对士兵的调动,使得所有士兵的纵坐标相同(即所有 y y y坐标相等,平行于 x x x 轴),且它的 x x x 轴的坐标是相邻的,并且不能两个士兵同时站在一个位置上。

题解

我们把 x x x y y y 拆开来分析,最终要求所有人处于同一Y坐标,不同X坐标。

  • 先对 y y y 轴方向分析。假设他们的X都相等(在同一竖线上,平行 y y y轴),就是在Y中选取一个点,使得这个点到所有点的距离最小,即Y方向上所需要移动的最小步数。按照货舱选址的解法,|Y1-Y|+|Y2-Y|+……+|Yn-Y| Y取中位数即得最小结果
  • 再来看 x x x 轴方向。假设他们的Y都相等(在同一横线上,平行 x x x轴)。 按照X从小到大排序,点在序列中的相对位置与最终在坐标系中的相对位置相同。设X为最终状态下最左边的点。则 |X1-X|+|X2-X-1|+……+|Xn-X-n+1|。(变换后最左边的横坐标为X,所以变换前第一个坐标X1要挪X步才能到X的位置,左边第二个坐标为X+1,而X2则需要挪X+1步就能到达左边第二个位置,即(X2-(X+1)))先将所有Xi减去i,即转化为货舱选址中的情况。|X1-X|+|X2-X|+……+|Xn-X|。
#include<iostream>
#include<algorithm>
#include<cstdio>
using namespace std;

const int N = 10010;

int x[N],y[N];

int main()
{
    int n,ans=0;
    scanf("%d",&n);
    for(int i=0;i<n;i++)
    {
        scanf("%d %d",x+i,y+i);
    }
    sort(x,x+n);
    sort(y,y+n);
    for(int i = 0;i<n;i++)
        x[i] -= i;
    sort(x,x+n);
    int midx = x[n/2],midy = y[n/2];  // 用变量把中间值存起来,减少在重复计算
    for(int i = 0;i<n;i++)
        ans += (abs(x[i]-midx) + abs(y[i]-midy));
    printf("%d",ans);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值