Cod sursa(job #1995832)

Utilizator deleted_2dbcc643895c1cb0DELETED deleted_2dbcc643895c1cb0 Data 29 iunie 2017 11:28:00
Problema Elementul majoritar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.72 kb
#include <fstream>
#define NMAX 1000000
using namespace std;
ifstream f("elmaj.in");
ofstream g("elmaj.out");
int v[NMAX+10],elmaj,cnt,i,n;
void _elmaj()
{
    elmaj = v[1];
    cnt = 0;

    for( i = 1; i <= n; i ++ )
    {
        if( elmaj == v[i] )
            cnt++;
        else
            cnt--;

        if ( cnt < 0 )
        {
            elmaj = v[i];
            cnt = 1;
        }
    }

    cnt = 0;

    for ( i = 1; i <= n; i ++)
        if ( v[i] == elmaj )
            cnt++;

    if( cnt >= n / 2 + 1 )
        g << elmaj << " " << cnt;
    else
        g << "-1";
}
int main()
{
    f >> n;
    for (i = 1; i<=n; i++)
        f >> v[i];
    _elmaj();

    return 0;
}