Cod sursa(job #2990491)

Utilizator stefan_dore_Stefan Dore stefan_dore_ Data 7 martie 2023 22:40:26
Problema Elementul majoritar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.71 kb
#include <iostream>
#include <fstream>
using namespace std;

const int NMAX = 1000001;
int n, cand, nr=0;
int V[NMAX];

ifstream f ("elmaj.in");
ofstream g ("elmaj.out");

void verif(int cand) {
    int cnt = 0;
    for (int i=1; i<=n; i++)
        if (V[i] == cand)
            cnt ++;
    if (cnt > n/2) {
        g << cand << ' ' << cnt;
    } else {
        g << -1;
    }
}

int main()
{
    int x;
    f >> n;
    for (int i=1; i<=n; i++) {
        f >> x;
        V[i] = x;
        if (nr == 0) {
            cand = x;
            nr = 1;
        } else if (cand == x){
            nr ++;
        } else {
            nr --;
        }
    }
    verif(cand);
    return 0;
}