[ABC329D] Election Quick Report 题解

· · 题解

题目链接

洛谷

AtCoder

题意简述

给定 N 名候选人和 M 张选票,求每一次投票后获胜者是谁,若多个候选人票数相等,取编号较小者。

1\le N,M \le 2 \times 10^5

题目解法

考虑用一个桶储存每位候选人获得的票数。

如果每次投票都把桶扫一遍的时间复杂度为 \mathcal{O}(NM),无法通过此题。

通过观察可以发现,要成为获胜者有以下两种情况:

  1. 选票数量比原获胜者多
  2. 选票数量与原获胜者相等,编号比原获胜者小

我们可以将每次获胜者的选票数量储存在 maxn 中,将编号储存在 winner 中,在每次投票后,比较当前候选人与原获胜者,如果满足以上两个条件其一,就将获胜者改为当前候选人。

时间复杂度 \mathcal{O}(M)。

AC Code

/*
Problem:
D
By:
qifan_maker
*/
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int mod = 998244353;
const int MAXN = 100100;
int t[200100];
int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    //freopen(".in","r",stdin);
    //freopen(".out","w",stdout);
    int n,m;
    cin >> n >> m;
    int maxn=0,winner=1145141919;
    for (int i=1;i<=m;i++){
        int x;
        cin >> x;
        t[x]++;
        if (t[x] > maxn){
            maxn = t[x];
            winner = x;
        }
        else if (t[x] == maxn){
            winner = min(winner,x);
        }
        cout << winner << endl;
    }
    return 0;
}