Cod sursa(job #3362894)

Utilizator horia.boeriuBoeriu Horia Andrei horia.boeriu Data 13 august 2026 02:25:38
Problema Elementul majoritar Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.04 kb
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1000000;
int v[MAXN];
int readInt(FILE *fin) {
    int x;
    char ch;
    ch = fgetc(fin);
    while (isspace(ch)) {
        ch = fgetc(fin);
    }
    x = 0;
    while (isdigit(ch)) {
        x = x * 10 + ch - '0';
        ch = fgetc(fin);
    }
    return x;
}
int main()
{
    FILE *fin, *fout;
    int n, i, x, ap;
    fin = fopen("elmaj.in", "r");
    n = readInt(fin);
    ap = 0;
    x = -1;
    for (i = 0; i < n; i++) {
        v[i] = readInt(fin);
        if (v[i] == x) {
            ap++;
        } else {
            ap--;
            if (ap < 0) {
                ap = 0;
                x = v[i];
            }
        }
    }
    fclose(fin);
    ap = 0;
    for (i = 0; i < n; i++) {
        if (v[i] == x) {
            ap++;
        }
    }
    fout = fopen("elamj.out", "w");
    if (ap <= n / 2) {
        fprintf(fout, "-1\n");
    } else {
        fprintf(fout, "%d %d\n", x, ap);
    }
    fclose(fout);
    return 0;
}