Cod sursa(job #3246292)

Utilizator Andrei24543Andrei Hulubei Andrei24543 Data 2 octombrie 2024 17:33:26
Problema Elementul majoritar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.74 kb
#include <bits/stdc++.h>
using namespace std;

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

int n , a[1000005];

int main()
{
    int i , cnt , elmaj;
    fin >> n;
    for(i = 1;i <= n;i++)
        fin >> a[i];
    elmaj = a[1];
    cnt = 1;
    for(i = 2;i <= n;i++)
        if(a[i] == elmaj) cnt++;
        else
        {
            cnt--;
            if(cnt < 0)
            {
                elmaj = a[i];
                cnt = 1;
            }
        }
    cnt = 0;
    for(i = 1;i <= n;i++)
        if(a[i] == elmaj) cnt++;
    if(cnt >= n / 2 + 1) fout << elmaj << " " << cnt;
    else fout << "-1";
    return 0;
}
/**
5 3
4 -2 2 = 0
3 -1 5 = 3
2 0 -3 = -5
4 1 -3 = -8
5 -3 2 = 0
-------
1 1 0
*/