poj 1723 中位数

SOLDIERS
Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 8960 Accepted: 3133

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


到y轴的距离好办,按y轴坐标排序,求中位数,然后求所有到中位数的距离和。

  但是在x上怎么样才能最短呢?百思不得其解啊,最后看了这篇之后,豁然开朗。

  x轴方向,先把x[]排好序,要想移动的距离最短,那么这时的相对位置肯定不变。那么假设a是这个队列的最左边的x坐标,那么它们的关系就有就有

     x[0] -> a

  x[1]  -> a + 1

  x[2] -> a + 2

  ........

  x[i] -> a + i

  即

     x[0] -> a

  x[1] - 1 -> a

  x[2] - 2 -> a

  .......

  x[i] - i -> a

  也就是要把这些点移动到固定的一个点,那么我们只要求出x[i]-i的中位数,就可以求出x轴移动的最短距离了。

  那么我们就可以这样来做:对x,y排序, 然后再对x进行x[i] = x[i] - i,再排序,去除两个中位数,分别求距离的绝对值即可。


AC代码



import java.util.Arrays;
import java.util.Scanner;

public class Main{

	/**
	 * @param args
	 * 有N个士兵,每个士兵站的位置用一个坐标(x,y)表示,
	 * 现在要将N个士兵站在同一个水平线,即所有士兵的y坐标相同并且x坐标相邻,
	 * 每个士兵每次可以移动一个位置。求出最少的移动步数。
	 */
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner scan=new Scanner(System.in);
		int n=scan.nextInt();
		int ans=0;
		int a[]=new int[n];
		int b[]=new int [n];
		for(int i=0;i<n;i++){
			a[i]=scan.nextInt();
			b[i]=scan.nextInt();
		}
		Arrays.sort(a);
		Arrays.sort(b);
		for(int i=0;i<n;i++){
			a[i]-=i;
		}	
		Arrays.sort(a);
		for(int i=0;i<n;i++){
			ans+=Math.abs(a[i]-a[n/2])+Math.abs(b[i]-b[n/2]);
		}
		System.out.println(ans);
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值