Cod sursa(job #2666934)

Utilizator PletoPletosu Cosmin-Andrei Pleto Data 2 noiembrie 2020 17:01:45
Problema Elementul majoritar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.86 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin("elmaj.in");
ofstream fout("elmaj.out");

vector<int> V;

int main() {
    int N, candidat, counter;

    fin >> N;
    fin >> candidat;
    V.push_back(candidat);
    counter = 1;
    for (int x, i = 1; i < N; ++i) {
        fin >> x;
        V.push_back(x);

        if (candidat == x) {
            counter += 1;
        } else {
            counter -= 1;
            if (counter == 0) {
                candidat = x;
                counter = 1;
            }
        }
    }
    if (counter > 0) {
        counter = 0;
        for (int i = 0; i < N; ++i) {
            if (candidat == V[i]) {
                counter += 1;
            }
        }
        if (counter >= (N / 2 + 1)) {
            fout << candidat << ' ' << counter << '\n';
            return 0;
        }
    }
    fout << -1 << '\n';
    return 0;
}