Cod sursa(job #3221517)

Utilizator DobraVictorDobra Victor Ioan DobraVictor Data 7 aprilie 2024 12:28:40
Problema Hashuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.97 kb
#include <iostream>
#include <fstream>
#include <stdint.h>
#include <functional>

const int32_t MAX_N = 1000000;
const int32_t HASH_SIZE = 1000003;

struct Item {
    int32_t val;
    int32_t next;
};

int32_t table[HASH_SIZE];
Item vec[MAX_N];
int32_t freeList;

void Insert(int32_t x) {
    int32_t hash = std::hash<int32_t>()(x) % HASH_SIZE;

    for(int32_t ind = table[hash]; ind != -1; ind = vec[ind].next)
        if(vec[ind].val == x)
            return;
    
    int32_t ind = freeList;
    freeList = vec[ind].next;

    vec[ind].val = x;
    vec[ind].next = table[hash];
    table[hash] = ind;
}
void Erase(int32_t x) {
    int32_t hash = std::hash<int32_t>()(x) % HASH_SIZE;

    for(int32_t prev = -1, ind = table[hash]; ind != -1; prev = ind, ind = vec[ind].next) {
        if(vec[ind].val == x) {
            if(prev == -1) {
                table[hash] = vec[ind].next;
            } else {
                vec[prev].next = vec[ind].next;
            }
            
            return;
        }
    }
}
bool Exists(int32_t x) {
    int32_t hash = std::hash<int32_t>()(x) % HASH_SIZE;

    for(int32_t ind = table[hash]; ind != -1; ind = vec[ind].next)
        if(vec[ind].val == x)
            return true;
    
    return false;
}

int main() {
    for(int32_t i = 0; i != HASH_SIZE; ++i)
        table[i] = -1;

    for(int32_t i = 0; i != MAX_N - 1; ++i)
        vec[i].next = i + 1;
    vec[MAX_N - 1].next = -1;

    freeList = 0;

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

    int32_t n;
    fin >> n;

    for(int32_t i = 0; i != n; ++i) {
        int32_t c, x;
        fin >> c >> x;

        switch(c) {
        case 1:
            Insert(x);
            break;
        case 2:
            Erase(x);
            break;
        case 3:
            fout << Exists(x) << '\n';
            break;
        }
    }

    fin.close();
    fout.close();

    return 0;
}