Cod sursa(job #759622)

Utilizator test13test13 test13 Data 18 iunie 2012 19:22:50
Problema Elementul majoritar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.06 kb
#include <cstdio>
#include <fstream>
#include <algorithm>
#include <vector>
using namespace std;
#define LIM 666013

ifstream f("elmaj.in");
ofstream g("elmaj.out");

vector<int>h[LIM];
int n;

int hash(int x){
    return ((x>>2)*113)%LIM;
}

void insert(int x){
    int p=hash(x);
    h[p].push_back(x);
}

void elmaj(){
    int p = 1,el ,sol ,nr = 1;

    for(int i=2;i<LIM;i++)
    if(h[i].size()>h[p].size())p=i;
    sort(h[p].begin(),h[p].end());
   // for(int i=0;i<h[p].size();i++)printf("%d ",h[p][i]);

    el = h[p][0]; sol = 1;
    for(int i=1;i<h[p].size();i++)
    if(h[p][i]==h[p][i-1])
    {
        nr++;
        if(nr>sol)
        {
            sol = nr;
            el = h[p][i];
        }
    } else nr = 1;
    if(sol>n/2)g<< el << ' ' << sol <<'\n'; else g << "-1\n";
}

int main(){
    int x;
   // freopen("elmaj.in","r",stdin);
   // freopen("elmaj.out","w",stdout);
        f >> n;
        for(int i=1;i<=n;i++)
        {
            f >> x;
            insert(x);
        }
    elmaj();
        return 0;
}