Cod sursa(job #1259678)

Utilizator laurageorgescuLaura Georgescu laurageorgescu Data 10 noiembrie 2014 13:07:31
Problema Elementul majoritar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.69 kb
#include<fstream>

using namespace std;

ifstream fin( "elmaj.in" );
ofstream fout( "elmaj.out" );

const int nmax = 1000000;
int v[ nmax ];

int main() {
    int n, cand, k;
    fin >> n;
    cand = -1;
    k = 0;
    for( int i = 0; i < n; ++ i ) {
        fin >> v[ i ];
        if ( k == 0 ) {
            cand = v[ i ];
        }
        if ( v[ i ] == cand ) {
            ++ k;
        } else {
            -- k;
        }
    }
    k = 0;
    for( int i = 0; i < n; ++ i ) {
        if ( cand == v[ i ] ) {
            ++ k;
        }
    }
    if ( k > n / 2 ) {
        fout << cand << " " << k << "\n";
    } else {
        fout << "-1\n";
    }
    fin.close();
    fout.close();
    return 0;
}