Cod sursa(job #3260178)

Utilizator ShokapKaplonyi Akos Shokap Data 30 noiembrie 2024 14:51:58
Problema Elementul majoritar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.82 kb
#include <iostream>
#include <fstream>

using namespace std;


int main () {

    ifstream input ("elmaj.in");
    ofstream output ("elmaj.out");

    int n;
    input >> n;
    int arr[n];

    for (int i = 0; i < n; i++){
        input >> arr[i];
    }

    int i, candidate = -1, votes = 0;
    for (i = 0; i < n; i++) {
        if (votes == 0) {
            candidate = arr[i];
            votes = 1;
        }
        else {
            if (arr[i] == candidate)
                votes++;
            else
                votes--;
        }
    }
    int count = 0;
    for (i = 0; i < n; i++) {
        if (arr[i] == candidate)
            count++;
    }

    if (count > n / 2) {
        output << candidate << ' ' << count;
        goto end;
    }
    output << -1;
    end:
    return 0;
}