Cod sursa(job #2219004)

Utilizator AndreiOffCovaci Andrei-Ion AndreiOff Data 6 iulie 2018 18:41:43
Problema Elementul majoritar Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 2.17 kb
#include <iostream>
#include <fstream>
#include <vector>
#define NMAX 1000000 //2 097 152 (ceva random)
#define MOD 663001 //numar prim

using namespace std;

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

int n;

vector<int> v;

int generateKey(int value){ //functie pentru generarea cheii unei valori

    return value % MOD;

}

void majorityElement(int n, vector<int> v){

    vector<vector<pair<int, int>>> hashTable(NMAX); //hash table care retine perechi de forma (valoare, aparitii)
    vector<pair<int, int>>::iterator it;

    vector<int> arr; //vectorul tuturor elementelor distincte

    int x = 0, key = 0;

    bool isRepeating = 0, found = 0;

    for(int i = 0; i < n; i++){

        isRepeating = 0;   //variabila care imi spune daca elementul citit a fost gasit deja in hash table
        x = v[i];

        key = generateKey(x);   //generez cheia

            for(it = hashTable[key].begin(); it != hashTable[key].end(); it++)

                if((*it).first == x){ //daca il gasesc pe x in hash retin acest lucru si ii cresc numarul de aparitii

                    (*it).second += 1;
                    isRepeating = 1;

                    }

        if(!isRepeating){ //daca x nu s-a gasit in hash il adaug si in hash si in vectorul de elemente distincte

            arr.push_back(x);
            hashTable[key].push_back(make_pair(x, 1));

            }

    }

    for(int i = 0; i < arr.size(); i++){ //pentru fiecare element generez din nou cheia de care e legat si verific daca numarul sau de aparitii este mai mare ca n/2

        key = generateKey(arr[i]);

        for(it = hashTable[key].begin(); it != hashTable[key].end() && !found; it++){

            if((*it).second > n/2){ //daca este mai mare il afisez si retin faptul ca l-am gasit

                g<<(*it).first<<" "<<(*it).second;
                found = 1;

            }

        }

    }

    if(!found)  //daca nu l-am gasit inseamna ca nu am un element majoritar
        g<<"-1";

}

int main()
{

f>>n;

for(int i = 1; i <= n; i++){

    int y;
    f>>y;
    v.push_back(y);

}

majorityElement(n, v);

    return 0;
}