Cod sursa(job #1071221)

Utilizator IeewIordache Bogdan Ieew Data 2 ianuarie 2014 19:06:20
Problema Hashuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.33 kb
#include <fstream>

using namespace std;
#define NO_BUCKETS 157399

#define DEBUG false

#if DEBUG
#include <iostream>
#define INFILE "/Users/biordach/Documents/Xcode Projects/training/training/hashuri.in"
#define __OUT cout
#else
#define INFILE "hashuri.in"
#define OUTFILE "hashuri.out"
ofstream __OUT(OUTFILE);
#endif

int n;

struct node{
    int value;
    node* next;
}*first[NO_BUCKETS], *last[NO_BUCKETS];

void readInput();
void solve();
void printOutput();

int main(int argc, const char * argv[])
{
    readInput();
//  solve();
//  printOutput();

#if DEBUG == false
    __OUT.close();
#endif
    
    return 0;
}

int contains(int x){
    int bucket = x % NO_BUCKETS;
    if(first[bucket] == NULL){
        return 0;
    }
    
    if(last[bucket] -> value == x){
        return 1;
    }
    
    node *q = first[bucket];
    while(q){
        if(q->value == x){
            return 1;
        }
        q = q->next;
    }
    
    return 0;
}

void add(int x){
    node* newNode = new node;
    newNode->value = x;
    newNode->next = NULL;
    
    int bucket = x % NO_BUCKETS;
    if(first[bucket] == NULL){
        first[bucket] = last[bucket] = newNode;
    } else {
        last[bucket]->next = newNode;
        last[bucket] = newNode;
    }
}

void remove(int x){
    int bucket = x % NO_BUCKETS;
    if(first[bucket]->value == x){
        if(last[bucket] == first[bucket]){
            delete last[bucket];
            last[bucket] = first[bucket] = NULL;
            return;
        }
        node* next = first[bucket]->next;
        delete first[bucket];
        first[bucket] = next;
        return ;
    }
    
    node *previous = first[bucket], *current = first[bucket]->next;
    
    while(current -> value != x){
        previous = current;
        current = current -> next;
    }
    
    node *next = current->next;
    if(last[bucket] == current){
        last[bucket] = previous;
    }
    delete current;
    previous->next = next;
}

void readInput(){
    int op, x;
    ifstream in(INFILE);
    in>>n;
    for(int i=0;i<n;i++){
        in>>op>>x;
        if(op == 1){
            if(!contains(x))
                add(x);
        } else if(op == 2){
            if(contains(x))
                remove(x);
        } else if(op == 3){
            __OUT<<contains(x)<<'\n';
        }
    }
    in.close();
}

void solve(){
}

void printOutput(){
}