Cod sursa(job #3130993)

Utilizator stefanmo03Mocanu Stefan stefanmo03 Data 18 mai 2023 23:01:44
Problema Hashuri Scor 30
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.97 kb
//#include <iostream>
#include <vector>
#include <fstream>
//using namespace std;
std::ifstream cin("hashuri.in");
std::ofstream cout("hashuri.out");
template<const int size>
class Hash{
    std::vector<int> vals;
    std::vector<int> next;
    std::vector<int> start;
    std::vector<int> liber;
public:
    Hash(){vals.resize(1);
        next.resize(1);
        start.resize(size);
        liber.clear();
    }
    void add(int val){
        for(auto elem: vals)if(elem == val)return;
        int h = val % size;
        int poz;
        //cout<<"ok";
        if(!liber.empty()){
            //cout<<"ok1";
            poz = liber.back();
            //cout<<"ok1";
            liber.pop_back();
            vals[poz] = val;
            next[poz] = start[h];
        }else{
            //cout<<"ok";
            vals.push_back(val);
            //cout<<"ok";
            next.push_back(start[h]);
            //cout<<"ok";
            poz = vals.size() -1;
        }
        start[h] = poz;
    }
    void erase(int val){
        int h = val % size;
        int poz = start[h];
        if(vals[poz] == val){
            start[h] = 0;
            liber.push_back(poz);
        }
        while(next[poz]){
            if(vals[next[poz]]==val){
                liber.push_back(next[poz]);
                next[poz] = next[next[poz]];
                break;
            }
            poz = next[poz];
        }
    }
    bool find(int val){
        int h = val % size;
        int poz = start[h];
        while(poz){
            if(vals[poz]==val){
                return true;
            }
            poz = next[poz];
        }
        return false;
    }
};

int main() {
    int n;
    cin>>n;
    Hash<666013> hash;
    for(int i=0;i<n;i++){
        int comanda, nr;
        cin>>comanda>>nr;
        switch (comanda) {
            case 1:{hash.add(nr);break;}
            case 2:{hash.erase(nr);break;}
            case 3:{cout<<hash.find(nr)<<'\n';break;}
            default:{}
        }
    }
    return 0;
}