Cod sursa(job #1190039)

Utilizator acomAndrei Comaneci acom Data 24 mai 2014 12:54:37
Problema Elementul majoritar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.59 kb
#include<fstream>
using namespace std;
ifstream fin("elmaj.in");
ofstream fout("elmaj.out");
int n,nr,k,cand,a[1000005];
int main()
{
    int i;
    fin>>n;
    cand=-1;
    for (i=1;i<=n;++i)
    {
        fin>>a[i];
        if (!k)
            cand=a[i], k=1;
        else
        {
            if (cand==a[i]) ++k;
            else --k;
        }
    }
    if (cand<0)
    {
        fout<<"-1\n";
        return 0;
    }
    for (i=1;i<=n;++i)
        if (cand==a[i]) ++nr;
    if (nr>n/2)
        fout<<cand<<" "<<nr<<"\n";
    else
        fout<<"-1\n";
    return 0;
}