Cod sursa(job #3361569)

Utilizator ssofiaSava Sofia-Maria ssofia Data 25 iulie 2026 20:02:47
Problema Elementul majoritar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.74 kb
#include <iostream>
#include <fstream>
using namespace std;

int a[1000001];
ifstream fin("elmaj.in");
ofstream fout("elmaj.out");
int main() {
    int n, i, candidate, votes, freq;

    fin >> n;
    
    for ( i = 0; i < n; i++) {
        fin >> a[i];
    }
    candidate = 0;
    votes = 0;
    freq = 0;

    for ( i = 0; i < n; i++) {
        if (votes == 0) {
            candidate = a[i];
            votes = 1;
        } else if (a[i] == candidate) {
            votes++;
        } else {
            votes--;
        }
    }
    
    for ( i = 0; i < n; i++) {
        if (a[i] == candidate) {
            freq++;
        }
    }
    if (freq > n / 2) {
        fout << candidate << " " << freq;
    } else {
        fout << -1;
    }
    return 0;
}