首页 > 专题系列 > Java解POJ > POJ 3664 Election Time [解题报告] Java
2013
11-13

POJ 3664 Election Time [解题报告] Java

Election Time

问题描述 :

The cows are having their first election after overthrowing the tyrannical Farmer John, and Bessie is one of N cows (1 ≤ N ≤ 50,000) running for President. Before the election actually happens, however, Bessie wants to determine who has the best chance of winning.

The election consists of two rounds. In the first round, the K cows (1 ≤ KN) cows with the most votes advance to the second round. In the second round, the cow with the most votes becomes President.

Given that cow i expects to get Ai votes (1 ≤ Ai ≤ 1,000,000,000) in the first round and Bi votes (1 ≤ Bi ≤ 1,000,000,000) in the second round (if he or she makes it), determine which cow is expected to win the election. Happily for you, no vote count appears twice in the Ai list; likewise, no vote count appears twice in the Bi list.

输入:

* Line 1: Two space-separated integers: N and K
* Lines 2..N+1: Line i+1 contains two space-separated integers: Ai and Bi

输出:

* Line 1: The index of the cow that is expected to win the election.

样例输入:

5 3
3 10
9 2
5 6
8 4
6 5

样例输出:

5

解题代码:

//* @author 洪晓鹏<[email protected]>
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;

public class Main {
	static class vote {
		int first;
		int second;
		int index;
	}

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int N = in.nextInt();
		int K = in.nextInt();
		// vote[] voters = new vote[N];
		ArrayList< vote> voters = new ArrayList< vote>();
		for (int i = 0; i < N; i++) {
			vote temp = new vote();
			temp.first = in.nextInt();
			temp.second = in.nextInt();
			temp.index = i + 1;
			voters.add(temp);
		}
		Collections.sort(voters, new Comparator< Object>() {
			public int compare(Object o1, Object o2) {
				vote a = (vote) o1;
				vote b = (vote) o2;
				return b.first - a.first;
			}

		});
		
		int result = 0;
		for (int i = 1; i < K; i++) {
			if (voters.get(result).second < voters.get(i).second) {
				
				result = i;
			}
		}
		System.out.println(voters.get(result).index);
	}
}

  1. simple, however efficient. A lot of instances it is difficult to get that a??perfect balancea?? among usability and appearance. I must say that youa??ve done a exceptional task with this. Also, the blog masses quite fast for me on Web explore.

  2. 站长,你好!
    你创办的的网站非常好,为我们学习算法练习编程提供了一个很好的平台,我想给你提个小建议,就是要能把每道题目的难度标出来就好了,这样我们学习起来会有一个循序渐进的过程!