Cod sursa(job #1762623)

Utilizator CaterpillerLeaf Caterpiller Caterpiller Data 23 septembrie 2016 21:56:28
Problema Elementul majoritar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.23 kb
#include <fstream>
#include <vector>
#include <utility>

std::pair<int, int> getMajoritary(std::vector<int>& v)
{
    if (v.empty()) return std::make_pair(-1, 0);
    int current_majoritary, n_appearances;
    current_majoritary = v[0];
    n_appearances = 1;
    for (int i = 1; i < v.size(); ++i) {
        if (v[i] == current_majoritary) {
            ++n_appearances;
        } else {
            --n_appearances;
            if (n_appearances == 0) {
                current_majoritary = v[i];
                n_appearances = 1;
            }
        }
    }
    n_appearances = 0;
    for (int x : v) {
        if (x == current_majoritary) ++n_appearances;
    }
    if (n_appearances * 2 >= v.size()) return std::make_pair(current_majoritary, n_appearances);
    else return std::make_pair(-1, 0);
}

int main()
{
    std::ifstream input("elmaj.in");
    std::ofstream output("elmaj.out");
    int n;
    std::vector<int> v;

    input >> n;
    for (int tmp, i = 0; i < n; ++i) {
        input >> tmp;
        v.push_back(tmp);
    }

    auto result = getMajoritary(v);
    if (result.first == -1) output << "-1\n";
    else output << result.first << ' ' << result.second << '\n';

    return 0;
}