Skip to content

Instantly share code, notes, and snippets.

@rendon
Created September 27, 2021 18:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rendon/3e98ab6ca873f741513cbed956995bd8 to your computer and use it in GitHub Desktop.
Save rendon/3e98ab6ca873f741513cbed956995bd8 to your computer and use it in GitHub Desktop.
#include <bits/stdc++.h>
using std::vector;
using std::pair;
using std::set;
using std::unordered_map;
using std::unordered_set;
void updateIndex(vector<int> const& ballot, int& index, unordered_set<unsigned> const& losers, int C) {
while (index < C) {
int candidate = ballot[index];
if (losers.find(candidate) == end(losers)) {
break;
}
index++;
}
}
pair<unsigned, int> findMinResult(unordered_map<int, int> const& results) {
pair<int, int> answer{0, std::numeric_limits<int>::max()};
for (auto entry : results) {
if (entry.second < answer.second) {
answer = entry;
}
}
return answer;
}
pair<unsigned, int> findMaxResult(unordered_map<int, int> const& results) {
pair<int, int> answer{0, 0};
for (auto entry : results) {
if (entry.second > answer.second) {
answer = entry;
}
}
return answer;
}
unsigned findWinner(vector<vector<int>> const& ballots, int C, int V) {
vector<int> I(V, 0);
unordered_set<unsigned> losers;
for (int op = 0; op < C; op++) {
unordered_map<int, int> results;
for (int i = 0; i < V; i++) {
int& index = I[i];
auto ballot = ballots[i];
updateIndex(ballot, index, losers, C);
if (index >= C) {
// We already processed the ballots C times and still have no winner. No one wins.
return 0;
}
int candidate = ballot[index];
results[candidate]++;
}
auto maxResult = findMaxResult(results);
if (maxResult.second > 0.5L * V) {
return maxResult.first + 1;
}
auto minResult = findMinResult(results);
for (auto entry : results) {
if (entry.second == minResult.second) {
losers.insert(entry.first);
}
}
}
return 0; // No one wins
}
int main() {
int C, V;
std::cin >> C >> V;
vector<vector<int>> ballots(V);
for (int v = 0; v < V; v++) {
for (int c = 0; c < C; c++) {
int vote;
std::cin >> vote;
ballots[v].push_back(vote - 1);
}
}
std::cout << findWinner(ballots, C, V) << "\n";
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment