Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

JAVA 解法,供大家参考

Posted by jackchongs at 2013-05-24 11:00:26 on Problem 1723
先将他们移动到同一横排,这横排应该是他们纵坐标的中位数,才能使得此过程总步数最少。然后要把他们紧凑起来。我们先把横坐标排序,并假设起点是a,那么我们就是要求i=1~n,abs(a+i - xi)的加和。即i=1~n,abs(a-(xi - i))的加和。我们构建一个新数列zi = xi - i,当a 等于z的中位数时原式的值最小。


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.StringTokenizer;

public class Main {

	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int num = Integer.valueOf(br.readLine());
		
		List<Integer> xList = new ArrayList<Integer>();
		List<Integer> yList = new ArrayList<Integer>();
		
		
		for (int i = 0; i < num; i++) {
			StringTokenizer stoken 
			            = new StringTokenizer( br.readLine()," ");
			xList.add(Integer.valueOf(stoken.nextToken()));
			yList.add(Integer.valueOf(stoken.nextToken()));
		}
		
		List<Integer> a = new ArrayList<Integer>();
		
		Collections.sort(xList);
		for (int i = 0; i < xList.size(); i++) {
			 a.add(xList.get(i) - i);
		}
		
		Collections.sort(a, new MyComparator());
//		System.out.println( a );
		Collections.sort(yList, new MyComparator());
//		System.out.println( yList );
		long sum = 0;
		

		int X = a.get(num/2);
		int Y = yList.get(num/2);
		for (int i = 0; i < yList.size() ; i++) {
			sum +=Math.abs ( yList.get(i) - Y );
		}
//		System.out.println(sum);
		
		for (int i = 0; i < a.size(); i++) {
			sum += Math.abs(a.get(i)- X);
		}
		
		System.out.println(sum);
		br.close();
	}

}


class MyComparator implements Comparator<Integer>
{
	public int compare(Integer a , Integer b)
	{
		if( a > b ) 
		{
			return 1;
		}
		else if( a.equals(b)) 
		{
			return 0;
		}
		else 
		{
			return -1;
		}
	}
}

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator