Cod sursa(job #963936)

Utilizator mlupseLupse-Turpan Mircea mlupse Data 19 iunie 2013 19:13:44
Problema Elementul majoritar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.78 kb
#include <fstream>
#define NMax 1000005
using namespace std;
ifstream fin("elmaj.in");
ofstream fout("elmaj.out");

int N,X[NMax],cand,k,NrSol;

void Read()
{
    fin>>N;
    for(int i=1;i<=N;i++)
        {
            fin>>X[i];
        }

}

void Solve()
{
    for(int i=1;i<=N;i++)
        {
            if(k==0)
                {
                    cand=X[i]; k=1;
                }
            else
                if(X[i]==cand)
                    k++;
                else
                    k--;
        }
    for(int i=1;i<=N;i++)
        if(X[i]==cand) NrSol++;
}
void Print()
{
    if(NrSol<N/2+1)
      fout<<"-1\n";
    else
        fout<<cand<<" "<<NrSol<<"\n";
}

int main()
{
    Read();
    Solve();
    Print();
    return 0;
}