Cod sursa(job #3130423)

Utilizator Roxana_3Asavei Roxana Roxana_3 Data 17 mai 2023 19:13:23
Problema Elementul majoritar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.74 kb
#include <bits/stdc++.h>
#define N 1000000
using namespace std;

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

int n, a[N + 5];

void Citire()
{
    fin >> n;
    for(int i = 1; i <= n; ++i)
        fin >> a[i];
}

void Rezolvare()
{
    int cand = a[1], vot = 1;
    for(int i = 2; i <= n; ++i)
        if(a[i] == cand) vot++;
        else
        {
            if(vot == 0) cand = a[i], vot = 1;
            else vot--;
        }

    /// el a iesit invingator, dar are majoritatea?
    vot = 0;
    for(int i = 1; i <= n; ++i)
        if(a[i] == cand) vot++;

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

int main()
{
    Citire();
    Rezolvare();

    return 0;
}