Cod sursa(job #3246291)

Utilizator Andrei24543Andrei Hulubei Andrei24543 Data 2 octombrie 2024 17:28:20
Problema Elementul majoritar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.7 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 , cntmax;
    fin >> n;
    for(i = 1;i <= n;i++)
        fin >> a[i];
    sort(a + 1 , a + n + 1);
    cnt = cntmax = 1;
    elmaj = a[1];
    for(i = 2;i <= n;i++)
    {
        if(a[i] != a[i - 1]) cnt = 1;
        else cnt++;
        if(cnt > cntmax)
        {
            cntmax = cnt;
            elmaj = a[i];
        }
    }
    if(cntmax >= n / 2 + 1) fout << elmaj << " " << cntmax;
    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
*/