Cod sursa(job #2570526)

Utilizator NotTheBatmanBruce Wayne NotTheBatman Data 4 martie 2020 17:23:51
Problema Elementul majoritar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.83 kb
#include <fstream>
#include <cmath>
#include <iomanip>
using namespace std;

const int N = 1e6 + 5;

int a[N], n;

void Read ()
{
    ifstream fin ("elmaj.in");
    fin >> n;
    for (int i = 1; i <= n; i++)
       fin >> a[i];
}

void Solve ()
{
    int candidate = a[1], k = 1;
    for (int i = 2; i <= n; i++)
        if (a[i] == candidate) k++;
        else
        {
            k--;
            if (k < 0)
            {
                candidate = a[i];
                k = 1;
            }
        }
    int times = 0;
    for (int i = 1; i <= n; i++)
        if (a[i] == candidate) times++;
    ofstream fout ("elmaj.out");
    if (times >= n / 2 + 1) fout << candidate << " " << times << "\n";
    else fout << "-1\n";
    fout.close();
}

int main()
{
    Read();
    Solve();
    return 0;
}