Cod sursa(job #2866814)

Utilizator tomaionutIDorando tomaionut Data 9 martie 2022 23:36:49
Problema Elementul majoritar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.67 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin("elmaj.in");
ofstream fout("elmaj.out");
int n, a[1000005];

int main()
{
    int i, x, nr, cand;
    fin >> n;
    for (i = 1; i <= n; i++)
        fin >> a[i];
    nr = 1;
    cand = a[1];
    for (i = 2; i <= n; i++)
    {
        x = a[i];
        if (x == cand)
            nr++;
        else nr--;
        if (nr < 0)
        {
            cand = a[i];
            nr = 1;
        }
    }
    nr = 0;
    for (i = 1; i <= n; i++)
        if (a[i] == cand)
            nr++;

    if (nr >= n / 2 + 1)
        fout << cand << " " << nr << "\n";
    else fout << "-1\n";

    return 0;
}