Cod sursa(job #2189197)

Utilizator MarianConstantinMarian Constantin MarianConstantin Data 27 martie 2018 20:10:49
Problema Elementul majoritar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.91 kb
#include <iostream>
#include <fstream>
#include <list>
#define M 1000003

using namespace std;

list < pair < int, int > > v[M];

int hf(int x)
{
    return x%M;
}

int main()
{
    int n, x, f, p=0;
    list < pair < int, int > > :: iterator j, sol;
    ifstream fin("elmaj.in");
    ofstream fout("elmaj.out");
    fin >> n;
    for (int i=1; i<=n; i++)
    {
        fin >> x;
        f=hf(x);
        for (j=v[f].begin(); j!=v[f].end(); j++)
        {
            if (j->first==x)
            {
                j->second++;
                if (j->second>n/2)
                {
                    p=1;
                    sol=j;
                }
                break;
            }
        }
        if (j==v[f].end())
            v[f].push_back(make_pair(x, 1));
    }
    if (p)
        fout << sol->first << " " << sol->second;
    else
        fout << -1;
    return 0;
}