Cod sursa(job #3205230)

Utilizator andreidumitrache1709Dumitrache Andrei Bogdan andreidumitrache1709 Data 19 februarie 2024 09:36:35
Problema Elementul majoritar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.76 kb
#include <bits/stdc++.h>
#define MAXN 1000000
using namespace std;
int v[MAXN + 1];
int main() {
    ifstream cin ( "elmaj.in" );
    ofstream cout ( "elmaj.out" );
    ios_base::sync_with_stdio( false );
    cin.tie( NULL );
    cout.tie( NULL );
    int n , i , ap , maj;
    cin >> n >> v[0];
    ap = 1;
    maj = v[0];
    for ( i = 1 ; i < n ; i++ ) {
        cin >> v[i];
        if ( v[i] != maj ) {
            ap--;
            if ( ap < 0 ) {
                maj = v[i];
                ap = 1;
            }
        } else
            ap++;
    }
    ap = 0;
    for ( i = 0 ; i < n ; i++ )
        ap += ( v[i] == maj );
    if ( ap > n / 2 )
        cout << maj << ' ' << ap << '\n';
    else
        cout << "-1\n";
    return 0;
}