Cod sursa(job #2587873)

Utilizator k2e0e0w3qDumitrescu Gheorghe k2e0e0w3q Data 23 martie 2020 17:52:31
Problema Elementul majoritar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.76 kb
#include <fstream>
#include <cstdlib>
using namespace std;

int main (void) {
    ifstream fin ("elmaj.in");
    ofstream fout ("elmaj.out");
    ios::sync_with_stdio(false);
    fin.tie(NULL);
    fout.tie(NULL);

    int n, *v, i;
    fin >> n;
    v=(int*)calloc(n, sizeof(int));

    fin >> v[0];
    int can=v[0], ap=1;
    for (i=1; i<n; i++) {
        fin >> v[i];
        if (v[i]==can)
            ap++;
        else {
            --ap;
            if (!ap) {
                can=v[i];
                ap++;
            }
        }
    }

    ap=0;
    for (i=0; i<n; i++)
        if (v[i]==can)
            ap++;

    if (ap>(n>>1))
        fout << can << ' ' << ap << '\n';
    else
        fout << "-1\n";
    return 0;
}