Cod sursa(job #1311005)

Utilizator TodeTodeAlexandru Toderica TodeTode Data 7 ianuarie 2015 17:00:59
Problema Elementul majoritar Scor 100
Compilator cpp Status done
Runda Teme Pregatire ACM Unibuc 2013 Marime 0.68 kb
#include <fstream>
#include <algorithm>

using namespace std;

int a[1000005];

int main()
{
    int n, x, i, cnt;
    ifstream fin("elmaj.in");
    fin >> n;
    for(i = 1; i <= n; i++) fin >> a[i];
    fin.close();
    x = a[1]; cnt = 1;
    for(i = 2; i <= n; i++)
    {
        if(x == a[i]) cnt++;
        else
        {
            cnt--;
            if(cnt < 0)
            {
                cnt = 1;
                x = a[i];
            }
        }
    }
    cnt = 0;
    for(i = 1; i <= n; i++) if(a[i] == x) cnt++;
    ofstream fout("elmaj.out");
    if(cnt > n / 2) fout << x << " " << cnt;
    else fout << "-1";
    fout.close();
    return 0;
}