Official

D - Election Quick Report Editorial by en_translator


There is an important property, as follows:

  • The winner when counting only the first \((i+1)\) votes is either the winner for the first \(i\) votes, or the candidate for which vote \((i+1)\) is.

By this property, it turns out that the answer can be found by managing the number of votes for each candidate and the winner when counting only the first \(i\) votes, comparing the number of votes for that temporal winner and the candidate for which vote \((i+1)\) is, thus updating the winner counting only the first \(i\) votes, for each \(i = 1, 2, \ldots, N\).

#include <iostream>
#include <vector>
using namespace std;

int main() {
	int n, m;
	cin >> n >> m;
	vector<int> a(m);
	for (int i = 0; i < m; i++) cin >> a[i];
	vector<int> cnt(n + 1); // Votes for each candidate
	int ans = 0; // Current winner
	for (int i = 0; i < m; i++) {
		cnt[a[i]]++;
		if (cnt[ans] < cnt[a[i]]) ans = a[i];
		else if (cnt[ans] == cnt[a[i]]) ans = min(ans, a[i]);
		cout << ans << '\n';
	}
}

posted:
last update: