Cod sursa(job #1874289)

Utilizator jurjstyleJurj Andrei jurjstyle Data 9 februarie 2017 21:09:28
Problema Elementul majoritar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.41 kb
#include <chrono>
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <fstream>

using namespace std;

ifstream f("elmaj.in");
ofstream g("elmaj.out");

int n;
int v[1000002];

int main()
{
    auto start_time = chrono::high_resolution_clock::now();
    srand(time(0));
    f >> n;
    for (int i = 1; i <= n; ++i)
        f >> v[i];
    bool ok = true;
    while (ok)
    {
        auto current_time = std::chrono::high_resolution_clock::now();
        if (chrono::duration_cast<std::chrono::milliseconds>(current_time - start_time).count() > 320)
        {
            if (ok == true)
            {
                g << "-1";
                return 0;
            }
        }
        else
        {
            bool find_indice = false;
            int indice;
            while (find_indice == false)
            {
                if (n < 30000)
                    indice = rand() % n + 1;
                else
                    indice = (rand() % n + 1) * 25;
                if (indice >= 1 && indice <= n)
                    find_indice = true;
            }
            int val = v[indice], cnt = 0;
            for (int i = 1; i <= n; ++i)
                if (v[i] == val)
                    ++cnt;
            if (cnt > n / 2)
            {
                g << val << " " << cnt ;
                return 0;
            }
        }
    }
    return 0;
}