Cod sursa(job #2905183)

Utilizator andiRTanasescu Andrei-Rares andiR Data 20 mai 2022 00:32:59
Problema Elementul majoritar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.58 kb
#include <bits/stdc++.h>

#define Nmax 1000000
using namespace std;
ifstream fin ("elmaj.in");
ofstream fout ("elmaj.out");
int n,i,v[Nmax],cand,nrapp;
int main()
{
    fin>>n;
    for (i=0;i<n;i++)
    {
        fin>>v[i];
        if (v[i]==cand)
            nrapp++;
        else if (nrapp==0)
        {
            cand=v[i];
            nrapp++;
        }
        else nrapp--;

    }
    nrapp=0;
    for (i=0;i<n;i++)
        if (cand==v[i])
            nrapp++;
    if (nrapp>=n/2+1)
        fout<<cand<<' '<<nrapp;
    else fout<<"-1";
    return 0;
}