Cod sursa(job #1947793)

Utilizator tudoras8tudoras8 tudoras8 Data 31 martie 2017 12:55:39
Problema Elementul majoritar Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 0.88 kb
#include <iostream>
#include <fstream>

using namespace std;

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++;
        } else if (v[i] == cand) {
            k++;
        } else {
            k--;
        }
    }
    
    if (cand < 0) {
        cout << "-1";
        return;
    }
    
    int count = 0;
    for (int i = 0; i < n; i++) {
        if (v[i] == cand) {
            count++;
        }
    }
    if (count >= n / 2 + 1) {
        cout << cand << ' ' << count << '\n';
    } else {
        cout << "-1";
    }
}

int main(int argc, const char * argv[]) {
    ifstream cin("elmaj.in");
    ofstream cout("elmaj.out");
    
    cin >> n;
    for (int i = 0; i < n; ++i) {
        cin >> v[i];
    }
    
    mooreMajority();
    
    return 0;
}