Cod sursa(job #730902)

Utilizator repp4raduRadu-Andrei Szasz repp4radu Data 7 aprilie 2012 01:00:03
Problema Elementul majoritar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.66 kb
#include <fstream>

using namespace std;

const int MAX = 1000050;
int n, v[MAX], maj, contor;

int main()
{
    ifstream in("elmaj.in");
    ofstream out("elmaj.out");
    in>>n;
    for(int i = 1; i <= n; i++) in>>v[i];
    for(int i = 1; i <= n; i++)
        if(v[i] == maj)
            contor++;
        else
        {
            contor--;
            if(contor < 0)
            {
                maj = v[i];
                contor = 1;
            }
        }
    contor = 0;
    for(int i = 1; i <= n; i++) if(v[i] == maj) contor++;
    if(contor >= (n / 2) + 1)
        out<<maj<<" "<<contor;
    else
        out<<"-1";
    return 0;
}