Cod sursa(job #2198391)

Utilizator PushkinPetolea Cosmin Pushkin Data 24 aprilie 2018 13:35:49
Problema Elementul majoritar Scor 100
Compilator cpp Status done
Runda Teme Pregatire ACM Unibuc 2013 Marime 0.94 kb
#include <iostream>
#include <bits/stdc++.h>
#include <fstream>
using namespace std;
#define MOD 666013
ifstream f("elmaj.in");
ofstream g("elmaj.out");
struct el
{
    int x, ap;
    el(int xx, int app=1)
    :x(xx), ap(app){}
};
vector<el> G[MOD];
int n, x, elm=-1, apr;
inline int locate(int x)
{
    int lst=x%MOD;
    for(unsigned int i=0;i<G[lst].size();i++)
        if(G[lst][i].x==x)
            return i;
    return -1;
}
inline bool add(int x)
{
    int lst=x%MOD, p=locate(x);
    if(p==-1)
        G[lst].push_back(el(x));
    else
    {
        G[lst][p].ap++;
        if(G[lst][p].ap>=n/2+1)
        {
            elm=G[lst][p].x;
            apr=G[lst][p].ap;
            return 1;
        }
    }
    return 0;
}
int main()
{
    f>>n;
    while(f>>x&&!add(x));
    while(f>>x)if(x==elm)
        apr++;
    g<<elm;
    if(elm!=-1)
        g<<' '<<apr;
    f.close();
    g.close();
    return 0;
}