Cod sursa(job #1249472)

Utilizator okros_alexandruOkros Alexandru okros_alexandru Data 26 octombrie 2014 23:50:20
Problema Elementul majoritar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.95 kb
#include <fstream>

#define Nmax 1000100

using namespace std;

int candidate, votes, N, A[Nmax];

void Solve() {

    candidate = A[1];
    votes = 1;

    for(int i = 2; i <= N; i++) {

        if(candidate == A[i])
            votes++;
        else
            votes--;

        if(votes == 0) {
            candidate = A[i];
            votes = 1;
            }

        }

    votes = 0;

    for(int i = 1; i <= N; i++)
        if(A[i] == candidate)
            ++votes;

    if(votes < N / 2 + 1)
        candidate = 0;

}
void Read() {

    ifstream in("elmaj.in");
    in >> N;

    for(int i = 1; i <= N; i++)
        in >> A[i];

    in.close();

}
void Write() {

    ofstream out("elmaj.out");

    if(candidate != 0)
        out << candidate << ' ' << votes << '\n';
    else
        out << "-1\n";

    out.close();

}
int main() {

    Read();
    Solve();
    Write();

    return 0;

}