Cod sursa(job #3349810)

Utilizator sweetcitrusflowerHancu Alexandru-Andrei sweetcitrusflower Data 2 aprilie 2026 16:34:34
Problema Elementul majoritar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.96 kb
#include <fstream>
#include <random>
#include <vector>
#include <algorithm>

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

int n;

int gasesteElMaj(const std::vector<int>& v) {    
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> dist(0, n - 1);

    int elemRand = v[dist(gen)];
    if (std::count(v.begin(), v.end(), elemRand) >= n / 2 + 1)
        return elemRand;
    return -1;
}

int main() {
    fin >> n;
    std::vector<int> v(n);
    for (int i = 0; i < n; i++)
        fin >> v[i];
    std::vector<int> afisat;
    afisat.push_back(-1);
    for(int k = 20; k; k--){
        int elmaj = gasesteElMaj(v);
        if(std::count(afisat.begin(), afisat.end(), elmaj) == 0)
        {
            fout << elmaj << ' ' << std::count(v.begin(), v.end(), elmaj);
            afisat.push_back(elmaj);
        }
    }
    if(afisat.size() == 1){
        fout << -1;
    }
    return 0;
}