题目
Time limit: 3.000 seconds
解题思路
1.模拟题,一定要小心,把题意搞明白,并且把输入的各种情况都想清楚了再写代码
2.所有的细节都在代码里了,我已经将代码弄的极简洁极易懂了
3.当有人被淘汰出局时,不能把这些票加到现有的候选者上,必须重新计算。道理很简单但却不明显,一个出错的情况:假设1出局了,把这一票给了后面的2,下一局中2也出局了,它把自己这一票给了后面的3,此时1的那一票就被丢弃了。以前我就是这样做的,但这种错误的做法居然通过了这些测试,真不知道是幸运还是不幸。
4.设n为票数,m是候选人数,那么时间复杂度是Θ(n*m),空间复杂度也是Θ(n*m)
通过代码
#include<stdio.h>
#include<string.h>
char name[21][81];
int vote[21];
bool out[21];
int choice[1000][20];
char tmp[70];
//num[] must be big enough and 0, n is the number of digits
//this function can deal with any situation
void str_to_ints(char *str,int *num,int n){
int carry=1;
for(int i=strlen(str)-1;i>=0;--i){
if(str[i]>='0'&&str[i]<='9'){
if(carry==1)
--n;
num[n]+=(str[i]-'0')*carry;
carry*=10;
}
else
carry=1;
}
}
int main(){
int N; //the number of cases
int n; //the number of candidates
int voter; //the number of voters
//#define DEBUG
#ifdef DEBUG
freopen("input","r",stdin);
freopen("output","w",stdout);
#endif
scanf("%d",&N);
for(int i=0;i<N;++i){
scanf("%d\n",&n); //read names
for(int j=1;j<=n;++j)
gets(name[j]);
memset(choice,0,sizeof(choice)); //read voters
voter=0;
while(true){
if(gets(tmp)==NULL||strlen(tmp)==0)
break;
str_to_ints(tmp,choice[voter],n);
voter++;
}
memset(vote,0,sizeof(vote)); //init
memset(out,0,sizeof(out));
for(int j=0;j<voter;++j)
vote[choice[j][0]]++;
while(true){ //loop
int max[2];
int min=1005;
max[0]=-1;
for(int j=1;j<=n;++j){
if(vote[j]>max[0] && out[j]==false){
max[0]=vote[j];
max[1]=j;
}
if(vote[j]<min && out[j]==false)
min=vote[j];
}
if(max[0]>voter/2){ //find the winner
printf("%s\n",name[max[1]]);
break;
}
else
{
if(max[0]==min){ //find the ties
for(int j=1;j<=n;++j)
if(out[j]==false)
printf("%s\n",name[j]);
break;
}
for(int j=1;j<=n;++j) //recount
if(vote[j]==min && out[j]==false)
out[j]=true;
memset(vote,0,sizeof(vote));
for(int j=0;j<voter;++j){
int k=0;
while(out[choice[j][k]] && k<n)
++k;
if(k<n)
vote[choice[j][k]]++;
}
}//end else
}
if(i!=N-1) //print '\n'
printf("\n");
}
return 0;
}