水题:票数统计 WA60分 大佬求助

题目描述
森林里举办篝火晚会,但是对于谁做篝火晚会的主持人,每个小动物都有自己的想法。有的说,应该让蹦蹦跳跳的兔子做主持,它最能带动氛围了;有的说,应该让声音动听的金丝雀做主持,它很容易吸引大家的注意力;有的说,应该让威严雄壮的大象做主持,它能够保证晚会的秩序……

动物们七嘴八舌的讨论着,最后决定投票决定。首先,他们给每位候选者发了一个编号,然后让这些候选者上台演讲为自己拉选票,最后,由各个动物在投票箱里投入自己支持的候选者编号(每位候选人的编号都是唯一的)。投票结束后,得票数最多的那位将成为主持人。

特别注意,如果得票最多的候选者不止一位,那这些候选者就属于这一轮的胜者;接下来动物们会在胜者中,再次举行选举。现在,请你做一下裁判,告诉大家选举结果吧!

输入格式
第 1 行一个整数 n,表示候选者人数;第 2 ∼ n + 1 行,每行两个数据 xi、si,分别代表第 i 位候选者的编号、名字;第 n+2 行有若干个数,表示投票箱里选票上候选者的编号。

输出格式
如果这轮选举能选出唯一的主持人,请输出成为主持人的候选者名字和它的得票数;否则,输出 “The following candidates will be voted on:”,接着是这一轮胜者的名字,每个一行按编号从小往大列出。

Input 1

5
2 Elephant
3 Canary
1 Rabbit
4 Fox
5 Deer
2 3 4 1 1 3 2 2 1 5 5 3 3

Output 1

Canary 4

Input 2

5
1 Rabbit
2 Canary
3 Elephant
4 Fox
5 Deer
2 2 3 3 4 4 1 1 1 2 3 5

Output 2

The following candidates will be voted on:
Rabbit
Canary
Elephant

image

#include<bits/stdc++.h>
using namespace std;
struct node{
    int id;
    string name;
    int vote;
}a[1005];
int tong[1005];
bool cmp(node x, node y){
    return x.vote >y.vote;
}
bool cmp2(node x, node y){
    return x.id < y.id;
}
int main(){
    int n,x;
    cin>>n;
    for(int i=1;i<=n;i++){
        cin>>a[i].id>>a[i].name;
    }
    while(cin>>x){
        tong[x]++;
    }
    for(int i=1;i<=n;i++){
        a[i].vote = tong[a[i].id];
    }
    sort(a+1,a+n+1,cmp);
    int cnt=0;
    for(int i=1;i<=n;i++){
        if(a[i].vote == a[1].vote){
            cnt++;
        }
    }   
    if(cnt==1){
        cout<<a[1].name<<" "<<a[1].vote;
    }
    else{
        cout<<"The following candidates will be voted on:"<<endl;
        sort(a+1,a+n+1,cmp2);
        for(int i=1;i<=cnt;i++){
            cout<<a[i].name<<endl;
        }
    }
    return 0;
}
1 个赞

这里的sort范围错了,如果对整个序列排序,那就是输出id最小的前cnt个name了
应该改成:

sort(a+1,a+cnt+1,cmp2);
1 个赞