Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<bits/stdc++.h>
- using namespace std;
- int mod(long a, long b)
- {
- if(b < 0)
- return -mod(-a, -b);
- int ret = a % b;
- if(ret < 0)
- ret+=b;
- return ret;
- }
- struct Hashmap{
- vector<pair<int, int>> element;
- int a = 13;
- long m = 1e9 + 19;
- long capacity;
- long count = 0;
- long hash(long key) const{
- long c = a;
- long sum = 0;
- for (int i = 0; key != 0; ++i) {
- sum += mod((mod(key, 10) * c), m);
- c = mod((c * a), m);
- key/=10;
- }
- return sum %capacity;
- }
- void init(int size){
- this->element.resize(size);
- capacity = size;
- }
- void put(long key, long value){
- long hashed = hash(key);
- if(this->element[hashed].first == key){
- this->element[hashed].second = value;
- }else if(this->element[hashed].first == 0){
- this->element[hashed].first = key;
- this->element[hashed].second = value;
- }else if(this->element[hashed].first != 0){
- long temp = hashed + 1;
- while(this->element[temp].first != 0){
- if(temp < capacity){
- temp++;
- }else{
- temp = 0;
- }
- }
- this->element[temp].first = key;
- this->element[temp].second = value;
- }
- this->count++;
- }
- long get(long key) const{
- long hashed = hash(key);
- if(this->element[hashed].first == key){
- return this->element[hashed].second;
- }else{
- for(int i = hashed + 1; i < count; i++){
- if(i == count - 1){
- for(int j = 0; j < hashed; j++){
- if(this->element[j].first == key) return this->element[j].second;
- }
- break;
- }
- if(this->element[i].first == key) return this->element[i].second;
- }
- return -1;
- }
- }
- long delete_pair(int key){
- long hashed = hash(key);
- if(this->element[hashed].first == 0){
- return -1;
- }
- int val = this->element[hashed].second;
- this->element[hashed].second = 0;
- this->element[hashed].first = 0;
- return val;
- }
- };
- int main(){
- ios::sync_with_stdio(false);cin.tie(nullptr);cout.tie(nullptr);
- Hashmap hashmap;
- int n;
- cin >> n;
- hashmap.init(n + 1);
- vector<string> res;
- while(n--){
- string request;
- cin >> request;
- if(request == "get" || request == "delete"){
- int key;
- cin >> key;
- int ans;
- if(request == "get"){
- ans = hashmap.get(key);
- }else{
- ans = hashmap.delete_pair(key);
- }
- if(ans == -1){
- res.emplace_back("None");
- }else{
- res.push_back(to_string(ans));
- }
- }else if(request == "put"){
- int key;
- int value;
- cin >> key >> value;
- hashmap.put(key, value);
- }
- }
- for(const auto& el : res){
- cout << el << '\n';
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement