Cod sursa(job #3033534)

Utilizator daristyleBejan Darius-Ramon daristyle Data 24 martie 2023 08:54:42
Problema Elementul majoritar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.16 kb
#include <fstream>

using namespace std;
ofstream fout("elmaj.out");

const int N_MAX=1e6;
const int BUFFSIZE=1024*1024;
int v[N_MAX];
char rbuf[BUFFSIZE];
int rpos;
FILE* fin;

void InitRead(){
    fin=fopen("elmaj.in", "r");
    rpos=BUFFSIZE-1;
}

char ReadCh(){
    if(!(rpos=((rpos+1)&(BUFFSIZE-1))))
        fread(rbuf, 1, BUFFSIZE, fin);
    return rbuf[rpos];
}

int ReadInt(){
    int retval=0;
    char ch;
    while(!isdigit(ch=ReadCh()));
    do
        retval=retval*10+ch-'0';
    while(isdigit(ch=ReadCh()));
    return retval;
}

void FinRead(){
    fclose(fin);
}

int main(){
    InitRead();
    int n=ReadInt();
    for(int i=0; i<n; ++i)
        v[i]=ReadInt();

    int cand=v[0];
    int votes=1;
    for(int i=1; i<n; ++i)
        if(!votes){
            cand=v[i];
            votes=1;
        }else if(cand==v[i])
            ++votes;
        else
            --votes;

    votes=0;
    for(int i=0; i<n; ++i)
        if(v[i]==cand)
            ++votes;

    if(votes>n/2)
        fout<<cand<<' '<<votes<<'\n';
    else
        fout<<-1<<'\n';

    FinRead();
    fout.close();
    return 0;
}