Cod sursa(job #2434064)

Utilizator ShayTeodor Matei Shay Data 30 iunie 2019 15:38:52
Problema Hashuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.19 kb
#include <fstream>
#include <list>
#include <functional>


template <typename Tkey, typename Tvalue> struct info {
	Tkey key;
	Tvalue value;
};


template <typename Tkey, typename Tvalue> class Hashtable {
private:
    std::list<struct info<Tkey, Tvalue>> *H;
    int size;
    int capacity;

public:
	Hashtable(int capacity) {
        this->capacity = capacity;
        size = 0;
        H = new std::list<struct info<Tkey, Tvalue>> [capacity];
    }

    ~Hashtable() {
        H->clear();
        delete [] H;
    }

inline void put(Tkey key, Tvalue value) {
        typename std::list<struct info<Tkey, Tvalue>>::iterator it;
        int sw = 0;
        std::hash<Tkey> hash;
        int index = hash(key) % capacity;
        for (it = H[index].begin() ; it != H[index].end() ; ++it) {
            if (it->key == key) {
                it->value = value;
                sw = 1;
                break;
            }
        }

        if (sw == 0) {
            info<Tkey, Tvalue> *node = new info<Tkey, Tvalue>;
            node->key = key;
            node->value = value;
            H[index].push_back(*node);
            delete node;
            ++size;
        }
    }

inline void remove(Tkey key) {
		typename std::list<struct info<Tkey, Tvalue>>::iterator it;
		std::hash<Tkey> hash;
        int index = hash(key) % capacity;

		for (it = H[index].begin() ; it != H[index].end() ; ++it) {
		    if (it->key == key) {
		        H[index].erase(it);
		        break;
		    }
		}    
	}

inline bool has_key(Tkey key) {
		typename std::list<struct info<Tkey, Tvalue>>::iterator it;
		std::hash<Tkey> hash;
        int index = hash(key) % capacity;

		for (it = H[index].begin() ; it != H[index].end() ; ++it) {
		    if (it->key == key) {
		        return true;
		    }
		}

		return false;
	}
};

int main() {
	std::ifstream cin("hashuri.in");
	std::ofstream cout("hashuri.out");
	std::ios::sync_with_stdio(false);
	int n, op_type, x;

	cin >> n;
	Hashtable <int, int> hash = Hashtable<int, int>(n);

	for(int i = 0 ; i < n ; ++i) {
		cin >> op_type >> x;

		switch(op_type) {
			case 1: hash.put(x, i);
					break;
			case 2: hash.remove(x);
					break;
			default: cout << hash.has_key(x) << '\n';
					break;
		}
	}

	return 0;
}