Cod sursa(job #2445566)

Utilizator uvIanisUrsu Ianis Vlad uvIanis Data 4 august 2019 17:50:21
Problema Hashuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.57 kb
#include <fstream>
#include <random>   // for universal hashing
#include <time.h>   // for better randomization

//data structure that supports queries like deleting, pushing and searching
//works for any data type that supports "=" and "==" operators
template<class dataType>
class List{
private:
    struct Node{
        dataType value;
        Node* next{nullptr};
    };

    Node* head{nullptr};

public:
    bool search(dataType value){
        Node* temp = head;

        while(temp!=nullptr){
            if(temp->value == value) {
                return true;
            }

            temp = temp->next;
        }

        return false;
    }

     void push(dataType value){
        if(search(value)==true){
            return;
        }

        if(head == nullptr){
            head = new Node;
            head->value = value;
            return;
        }

        Node* temp = head;

        while(temp->next != nullptr){
            temp = temp->next;
        }

        temp->next = new Node;
        temp->next->value = value;
    }

    bool remove(dataType value){

        if(head != nullptr){
            if(head->value == value){
                head = head->next;
                return true;
            }
        }

        Node* temp = head;
        Node* parent = new Node;

        while(temp!=nullptr){
            if(temp->value == value){
                    parent->next = temp->next;
                    return true;
            }

            parent = temp;
            temp = temp->next;
        }

        return false;
    }


};

List<int> hashTable[100000];

int main()
{
   /* universal hash function idea: h(x) = (A*x mod p) mod M
      P - the least prime number greater than the maximum value of x (in our case 2 000 000 011)
      A - a random number between 1 and p-1
      M - the size of the hash table (let's consider it to be 100 000)

      so the function is h(x) = (A*x mod 2000000011) mod 100000
    */

    std::srand(time(nullptr));
    int A = rand()%2000000010 + 1;

    std::ifstream fin("hashuri.in");
    std::ofstream fout("hashuri.out");


    int N;  fin>>N;

    int op, x, index;
    while(N){
        fin>>op>>x;

        index = (1LL*A*x%2000000011)%100000;
        if(op==1){
            hashTable[index].push(x);
        }
        else if(op==2){
            hashTable[index].remove(x);
        }
        else {
            if(hashTable[index].search(x)==true) fout<<1<<"\n";
            else fout<<0<<"\n";
        }

        N--;
    }
}