跳到正文

题解

[ABC329D] Election Quick Report 题解

qifan_maker约 2 分钟
原文
文章信息与版本

文章信息

发布
2023年11月19日
收录
2026年2月2日
更新
2026年11月9日
篇幅
约 2 分钟

版本

  1. v1当前

题目链接

洛谷

AtCoder

题意简述

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

1≤N,M≤2×1051\le N,M \le 2 \times 10^5

题目解法

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

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

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

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

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

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

AC Code

C++
/*
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;
}
原文