Cod sursa(job #1074486)

Utilizator lorundlorund lorund Data 7 ianuarie 2014 18:17:29
Problema Elementul majoritar Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 0.78 kb
#include <cstdio>

int main()
{
    FILE *tin = fopen("elmaj.in", "r");
    int N;
    int maj=-1, c=0;

    //freopen("txt.in", "r", stdin);
    freopen("elmaj.out", "w", stdout);

    fscanf(tin, "%d", &N);
    for (int i=0; i<N; ++i){
        int x;

        fscanf(tin, "%d", &x);
        if (x==maj){
            ++c;
        }
        else{
            if (c){
                --c;
            }
            else{
                maj = x;
                c = 1;
            }
        }
    }
    fclose(tin);

    tin = fopen("txt.in", "r");
    c = 0;
    for (int i=0; i<N; ++i){
        int x;

        fscanf(tin, "%d", &x);
        c += x==maj;
    }

    if (c>=N/2)
        printf("%d", maj);
    else
        printf("-1");
    return 0;
}