Cod sursa(job #1651927)

Utilizator patrutoiuandreipatrutoiu andrei patrutoiuandrei Data 14 martie 2016 11:11:55
Problema Elementul majoritar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.78 kb
#include <fstream>

using namespace std;
ifstream fin("elmaj.in");
ofstream fout("elmaj.out");
const int Ndim = 1000001;
int V[Ndim],N,nr,sol;
void read()
{
    fin>>N;
    for(int i=1;i<=N;i++)
        fin>>V[i];
}
int elmaj()
{
    int cand = -1,k=0,i;
    for(i=1;i<=N;i++)
    {
        if(k==0)
        {
            cand = V[i];
            k=1;
        }
        else if(V[i] == cand)
            k++;
        else
            k--;
    }
    if(cand < 0)
        return -1;
    for(i=1;i<=N;i++)
    {
        if(V[i] == cand)
            nr++;
    }
    if(nr > N/2)
        return cand;
    return -1;
}
int main()
{
    read();
    sol = elmaj();
    if(sol != -1)
        fout<<sol<<' '<<nr;
    else
        fout<<sol;
    return 0;
}