Cod sursa(job #1499748)

Utilizator goalexboxerFMI Alexandru Ionascu goalexboxer Data 11 octombrie 2015 01:05:46
Problema Elementul majoritar Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 0.92 kb
/*

     Moore’s Voting Algorithm - implemented by Je

*/
#include<fstream>
#define MAXN 1000001
#define FIN "elmaj.in"
#define FOUT "elmaj.out"
using namespace std;

ifstream f(FIN);
ofstream g(FOUT);

int v[MAXN];
int n;


int main()
{
    f >> n;
    int x;

    //init first element
    f >> x;
    int candidate = 1;
    v[candidate] = x;
    int votes = 1;

    for(int i=2; i<=n; i++)
    {
        f >> v[i];

        if(v[candidate] == x)
        {
            votes++;

        }
        else if(votes > 1)
        {
            votes--;
        }
        else
        {
            candidate = x;
            votes = 1;
        }

    }

    int counter = 0;
    //cehck if is majority
    for(int i=1; i<=n; i++)
    {
        if(v[i] == v[candidate])
            counter++;
    }

    if(counter >= (n/2)+1)
    {
        g << v[candidate] << " " << counter;
    }
    else
    {
        g << "-1";
    }



    return 0;
}