2020 BIT冬训-C++STL G - SOLDIERS POJ - 1723

Problem 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



这题的思想是排序然后选择中位数(还需要灵活处理x轴的数据)。
且这题的x,y的坐标其实是没有关联的。也就是说可以分别单独处理。
对于y坐标,因为要在一条横线,所以距离为abs|yi-ymid|
即在y坐标的中位数处选择即可。
而对于x坐标,需要不重复的选择相邻的点,即一条横线。
令横线起点的坐标为a,则第i个x到a+i的距离为abs|xi-(a+i)|
即abs|(xi-i)-a|,a为xi-i的中位数。(0<=i<n)
AC代码如下
#include<stdio.h>
#include<algorithm>
using namespace std;
int x[10005],y[10005],n,xmid,ymid;
int main(){
    scanf("%d",&n);
    for(int i =0 ;i<n;i++){
        scanf("%d%d",&x[i],&y[i]);
    }
    sort(x,x+n);
    for(int i=0;i<n;i++)
        x[i]-=i;
    sort(x,x+n);
    sort(y,y+n);
    xmid = x[n/2];
    ymid = y[n/2];
    int ans = 0;
    for(int i=0;i<n;i++){ 
        ans+=abs(x[i]-xmid);
        ans+=abs(y[i]-ymid);
    }
    printf("%d\n",ans);
    return 0;
}

 

 
posted @ 2021-02-02 20:19  mikku  阅读(76)  评论(0)    收藏  举报