Official

B - Election Editorial by en_translator


In order to solve this problem, the knowledge of loop like how to use for statements is required. If you didn’t know, please take advantage of the opportunity to learn it.

There are at most \(N\) candidates, so count naively for each candidate how many people voted him/her.

There are several possible ways to find the candidate with the maximum votes. Please refer to the sample code below as an example.

The complexity is \(O(N^2)\), which is fast enough.

Sample code (C++)

#include <bits/stdc++.h>
using namespace std;

int main(){
    int n; cin >> n;
    vector<string> v(n);
    for(int i = 0; i < n; i++) cin >> v[i];
    int ma = 0;
    string res;
    for(int i = 0; i < n; i++){
        string kouho = v[i];
        int cnt = 0;
        for(int j = 0; j < n; j++) if(v[j] == kouho) cnt++;
        if(cnt > ma){
            ma = cnt;
            res = kouho;
        }
    }
    cout << res << endl;
}

posted:
last update: