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

POJ 2643 Election [解题报告] Java

Election

问题描述 :

Canada has a multi-party system of government. Each candidate is generally associated with a party, and the party whose candidates win the most ridings generally forms the government. Some candidates run as independents, meaning they are not associated with any party. Your job is to count the votes for a particular riding and to determine the party with which the winning candidate is associated.

输入:

The first line of input contains a positive integer n satisfying 2 <= n <= 20, the number of candidates in the riding. n pairs of lines follow: the first line in each pair is the name of the candidate, up to 80 characters; the second line is the name of the party, up to 80 characters, or the word "independent" if the candidate has no party. No candidate name is repeated and no party name is repeated in the input. No lines contain leading or trailing blanks.

The next line contains a positive integer m <= 10000, and is followed by m lines each indicating the name of a candidate for which a ballot is cast. Any names not in the list of candidates should be ignored.

输出:

Output consists of a single line containing one of:
  • The name of the party with whom the winning candidate is associated, if there is a winning candidate and that candidate is associated with a party.
  • The word “independent” if there is a winning candidate and that candidate is not associated with a party.
  • The word “tie” if there is no winner; that is, if no candidate receives more votes than every other candidate.

样例输入:

3
Marilyn Manson
Rhinoceros
Jane Doe
Family Coalition
John Smith
independent
6
John Smith
Marilyn Manson
Marilyn Manson
Jane Doe
John Smith
Marilyn Manson

样例输出:

Rhinoceros

解题代码:

//* @author: 82638882@163.com
import java.util.*;
public class Main
{
 public static void main(String[] args)
 {
	Scanner in=new Scanner(System.in);
	int n=in.nextInt();
	String[] ss1=new String[n];
	String[] ss2=new String[n];
	int[] p=new int[n];
	in.nextLine();
	for(int i=0;i< n;i++)
	{
	  ss1[i]=in.nextLine();
	  ss2[i]=in.nextLine();
	}
	int m=in.nextInt();
	in.nextLine();
	String s;
	for(int i=0;i< m;i++)
	{
	   s=in.nextLine();
	   for(int j=0;j< n;j++)
	   {
	     if(s.equals(ss1[j]))
		{
		   p[j]++;
		   break;
	 	}
	   }
	}
	int max=0,tag=-1;;
	boolean bb=false;
	for(int i=0;i< n;i++)
	{
	   if(p[i]>max){
		max=p[i];
		bb=false;
		tag=i;
	    }
	    else if(p[i]==max)bb=true;
	}
	if(bb) System.out.println("tie");
	else System.out.println(ss2[tag]);
   }
}

  1. 是穷举,但是代码有优化(v数组),并不是2^n。测试数据应该没问题,之前有超时的代码。