Cod sursa(job #1279649)

Utilizator Narcys01Ciovnicu Narcis Narcys01 Data 30 noiembrie 2014 18:18:49
Problema Elementul majoritar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.71 kb
#include <iostream>
#include <iostream>
#include <fstream>
#include <algorithm>

using namespace std;

int a[1000006];

int main()
{
    int n, i, j, k, v;
    bool falls;
    ifstream fin("elmaj.in");
    fin >> n;
    for (i = 1; i <= n; i++)
        fin >> a[i];
    fin.close();
    sort(a + 1, a + n + 1);
    k = n / 2 + 1;
    falls = true;
    i = j = k;
    v = a[k];
    while (falls)
    {
        if (v != a[i] && v != a[j]) falls = false;
        else if (j <= n && a[j] == v) j++;
        else if (i > 0 && a[i] == v) i--;
    }
    i++;
    ofstream fout("elmaj.out");
    if (j - i >= k) fout << v << " " << j - i;
    else fout << "-1";
    fout.close();
    return 0;
}