Cod sursa(job #3155583)

Utilizator andreiomd1Onut Andrei andreiomd1 Data 8 octombrie 2023 19:00:24
Problema Elementul majoritar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.79 kb
#include <iostream>
#include <cstdio>

using namespace std;

static constexpr int NMAX = (int)(1e6 + 1);

int n;
int a[NMAX];

namespace InParser
{
    static constexpr int BSIZE = (1 << 16);

    static int pos = (BSIZE - 1);
    static char buff[BSIZE];

    static inline char Char()
    {
        ++pos;

        if (pos == BSIZE)
        {
            int n = fread(buff, 1, BSIZE, stdin);
            if (n != BSIZE)
                for (int i = n; i < BSIZE; ++i)
                    buff[i] = 0;

            pos = 0;
        }

        return buff[pos];
    }

    inline int Int()
    {
        int ans = 0;

        for (;;)
        {
            char Ch = Char();

            if (Ch >= '0' && Ch <= '9')
            {
                ans = (int)(Ch - '0');
                break;
            }
        }

        for (;;)
        {
            char Ch = Char();

            if (Ch >= '0' && Ch <= '9')
                ans = ans * 10 + (int)(Ch - '0');
            else
                break;
        }

        return ans;
    }
};

int main()
{
    ios_base ::sync_with_stdio(false);
    cin.tie(nullptr);

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

    n = InParser ::Int();

    int candidate = 0, votes = 0;

    for (int i = 1; i <= n; ++i)
    {
        int x = InParser ::Int();
        if (i == 1)
            candidate = x;

        if (x == candidate)
            ++votes;
        else
            --votes;

        if (votes < 0)
            candidate = x, votes = 0;

        a[i] = x;
    }

    if (votes > 0)
    {
        printf("%d ", candidate);

        int counts = 0;

        for (int i = 1; i <= n; ++i)
            counts += (bool)(a[i] == candidate);

        printf("%d", counts);
    }
    else
        printf("-1");

    printf("\n");

    return 0;
}