Cod sursa(job #2214771)

Utilizator dahaandreiDaha Andrei Codrin dahaandrei Data 20 iunie 2018 00:59:07
Problema Elementul majoritar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.71 kb
#include <fstream>
#include <algorithm>
 
using namespace std;
 
ifstream in("elmaj.in");
ofstream out("elmaj.out");
 
const int MAXN = 1e6;

int cnt, n, v[MAXN + 1], i, e;
 
int main (){
    in >> n;
 
    for (int i = 1; i <= n; ++ i){
        in >> v[i];
    }
 
    for (i = 1; i <= n ;++ i){
        if (v[i] == e)
            cnt ++;
        if (v[i] != e)
            cnt --;
        if (v[i] != e && cnt <= 0){
            e = v[i];
            cnt = 1;
        }
    }
 
    cnt = 0;
    for (i = 1; i <= n; ++ i){
        if (v[i] == e)
            cnt ++;
    }
 
    if (cnt >= n / 2 + 1)
        out << e << " " << cnt;
    else
        out << -1;
 
 
 
    return 0;
}