题解:UVA10374 Election

· · 题解

UVA10374 Election 题解

题意

先给 n 个人名和其对应的政党名,再给 m 张票投给个人,求票数最多的候选人的政党。如果有多个候选人同票就输出 tie。

思路

直接模拟,由于数据很水 n 只有 20,所以可以用结构体直接把每个人的信息按下标存下来,然后暴力遍历。

代码

#include <bits/stdc++.h>
#define int long long
constexpr int N = 100+5;
using namespace std;
typedef pair<int,int> P;
struct node{
    string dang;
    int tot;
}e[N];
int T,n,m,idx=0;
map<string,int>id;
void print(int cnt,int ans){
    if(cnt <= 1)
        cout<<e[ans].dang<<'\n';
    else
        cout<<"tie"<<'\n';
    return;
}
signed main(){
    scanf("%d\n",&T);
    while(T--){
        id.clear();
        string name,pol,vot;
        int Max=0,now=0,ans=0;
        scanf("\n%d\n",&n);
        for(int i = 1 ; i <= n ; i++){
            getline(cin,name);
            getline(cin,pol);
            if(!id[name]) id[name] = ++idx;
            e[id[name]].tot = -1;
            e[id[name]].dang = pol;
        }
        scanf("%d\n",&m);
        for(int i = 1 ; i <= m ; i++){
            getline(cin,vot);
            int nid = id[vot];
            if(e[nid].tot != 0){
                if(e[nid].tot == -1) e[nid].tot = 1;
                else e[nid].tot += 1;
            } 
        }
        for(auto p : id){
            int nid = p.second;
            int tot = e[nid].tot;
            if(Max < tot){
                Max = tot;
                now = 1;
                ans = nid;
            }
            else if(Max == tot){
                now++;
            }
        }
        print(now,ans);
        if(T) cout<<'\n';
    }
}