Cod sursa(job #2760442)

Utilizator mihnea_buzoiuMihnea Buzoiu mihnea_buzoiu Data 26 iunie 2021 14:34:48
Problema Elementul majoritar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.83 kb
#include <iostream>
#include <stdio.h>

using namespace std;

const int N = 1e6+2;
int v[N];

int find_maj(int n){
    int cand = -1, freq = 0;
    for (int i=0; i<n; i++){
        scanf("%d", &v[i]);

        if (cand == v[i])
            freq++;
        else
        {
            if (freq > 0)
                freq--;
            else cand = v[i];
        }
    }
    return cand;
}

int check_maj(int c, int n){
    int f = 0;
    for (int i=0; i<n; i++){
        if (v[i] == c)
            f++;
    }
    return f;
}

int main()
{
    freopen("elmaj.in", "r", stdin);
    freopen("elmaj.out", "w", stdout);

    int n;
    scanf("%d", &n);

    int e = find_maj(n);
    int f = check_maj(e, n);

    if (f > n/2)
        printf("%d %d", e, f);
    else printf("-1");
}

/*
8
3 4 4 3 3 2 3 3
*/