Cod sursa(job #2718613)

Utilizator Stefan_XTRadu Stefan Rares Stefan_XT Data 8 martie 2021 21:32:45
Problema Elementul majoritar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.72 kb
#include <fstream>
#define ll long long
using namespace std;

ifstream fin("elmaj.in");
ofstream fout("elmaj.out");

ll a[1000006];

int main()
{
    ll n;
    fin >> n;

    for (ll i = 0; i < n; i++)
      fin >> a[i];

    ll cand = a[0], vot = 1;
    for (ll i = 1; i < n; i++)
    {
        if (a[i] == cand)
          vot++;
        else
          vot--;

        if (vot == 0)
          vot = 1, cand = a[i];
    }

    if (vot != 0)
    {
        vot = 0;
        for (int i = 0; i < n; i++)
            if (a[i] == cand) vot++;

        if (vot > n/2) fout << cand << " " << vot;
        else fout << -1;
    }
    else fout << -1;

    fin.close();
    fout.close();
    return 0;
}