Cod sursa(job #661692)

Utilizator ariel_roAriel Chelsau ariel_ro Data 14 ianuarie 2012 21:56:56
Problema Elementul majoritar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.89 kb
#include <fstream>

using namespace std;

#define NMAX 1000005

int N, a[NMAX];
ifstream in("elmaj.in");
ofstream out("elmaj.out");

void elmaj()
{
    int k = 1, el_maj = a[0];
    for (int i = 1; i < N; i++)
    {
        if (k == 0)
        {
            k++;
            el_maj = a[i];
        }
        else if (el_maj != a[i])
        {
            k--;
        }
        else if (el_maj == a[i])
        {
            k++;
        }
    }


    if (k > 0)
    {
        k = 0;
        for (int i = 0; i < N; i++)
        {
            if (a[i] == el_maj)
            {
                k++;
            }
        }
        out<<el_maj<<" "<<k<<endl;
    }
    else
    {
        out<<"-1";
    }
}

void cit()
{
    in>>N;
    for (int i = 0; i < N; i++)
    {
        in>>a[i];
    }
}

int main()
{
    cit();
    elmaj();
    return 0;
}