Cod sursa(job #1880496)

Utilizator FlowstaticBejan Irina Flowstatic Data 15 februarie 2017 19:55:42
Problema Elementul majoritar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.59 kb
#include <fstream>
#define NMAX 1000005
using namespace std;
ifstream fin("elmaj.in");
ofstream fout("elmaj.out");

int a[NMAX];
int main()
{
    int N;
    fin>>N;
    int cand, k = 0;
    for(int i=1;i<=N;i++)
    {
        fin>>a[i];
        if(k == 0)
            cand = a[i], k = 1;
        else
        {
            if(cand == a[i])
                k++;
            else
                k--;
        }
    }

    int nr = 0;
    for(int i=1;i<=N;i++)
        if(a[i] == cand)
            nr++;
    if(nr>N/2)
        fout<<cand<<" "<<nr<<'\n';
    else

        fout<<"-1"<<'\n';
    return 0;
}