Cod sursa(job #2723369)

Utilizator Victor2006Nicola Victor-Teodor Victor2006 Data 13 martie 2021 22:41:20
Problema Elementul majoritar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.72 kb
#include <fstream>
#define N 1000000

using namespace std;

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

int v[N + 1];
int n;

int main() {
    int cnt, nmaj, nr;
    fin >> n >> nmaj;
    v[1] = nmaj;
    cnt = 1;
    for ( int i = 2; i <= n; i ++ ) {
        fin >> v[i];
        if ( v[i] != nmaj ) {
            cnt --;
            if ( cnt < 0 ) {
                nmaj = v[i];
                cnt = 1;
            }
        }
        else
            cnt ++;
    }
    cnt = 0;
    for ( int i = 1; i <= n; i ++ ) {
        if ( v[i] == nmaj )
            cnt ++;
    }
    if ( cnt > n / 2 )
        fout << nmaj << " " << cnt << "\n";
    else
        fout << "-1\n";
    return 0;
}