Cod sursa(job #786515)

Utilizator sory1806Sandu Sorina-Gabriela sory1806 Data 11 septembrie 2012 15:52:42
Problema Elementul majoritar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.91 kb

#include <iostream>
#include <fstream>

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

const int MAX_N = 1000001;

int v[MAX_N];
int n;


int main()
{
    f >> n;
    for (int i = 0; i < n; i ++) {
        f >> v[i];
    }

    int count = 0, unpaired;

    for (int i = 0; i < n; i ++) {
        if (count == 0) {
            unpaired = v[i];
            count = 1;
        }
        else {
            if (v[i] == unpaired) {
                count ++;
            }
            else {
                count --;
            }
        }
    }

    if (count == 0) {
        g << -1 << '\n';
    }
    else {
        int no = 0;
        for (int i = 0; i < n; i ++) {
            if (v[i] == unpaired) {
                no ++;
            }
        }
        if (no >= n / 2 + 1) {
            g << unpaired << ' ' << no << '\n';
        }
        else {
            g << -1 << '\n';
        }
    }

    return 0;
}