Cod sursa(job #1947993)

Utilizator tudoras8tudoras8 tudoras8 Data 31 martie 2017 16:32:13
Problema Elementul majoritar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.86 kb
#include <iostream>
#include <fstream>

using namespace std;

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

const int MAXN = 1000001;
int n, v[MAXN];

void mooreMajority() {
    int cand = -1, k = 0;
    for (int i = 0; i < n; i++) {
        if (k == 0) {
            cand = v[i];
            k = 1;
        } else if (v[i] == cand) {
            k++;
        } else {
            k--;
        }
    }
    
    if (cand < 0) {
        out << cand;
        return;
    }
    
    int count = 0;
    for (int i = 0; i < n; i++) {
        if (v[i] == cand) {
            count++;
        }
    }
    if (count >= n / 2 + 1) {
        out << cand << ' ' << count << '\n';
    } else {
        out << "-1";
    }
}

int main(int argc, const char * argv[]) {
    in >> n;
    for (int i = 0; i < n; ++i) {
        in >> v[i];
    }
    
    mooreMajority();
    
    return 0;
}