Cod sursa(job #2191540)

Utilizator ibicecIT Zilla ibicec Data 2 aprilie 2018 23:38:07
Problema Hashuri Scor 0
Compilator java Status done
Runda Arhiva educationala Marime 2.28 kb
//package org.iuliu;

import java.io.*;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) throws IOException {
        FileInputStream input = new FileInputStream("hashuri.in");
        Scanner in = new Scanner(input);

        Writer out = new FileWriter("hashuri.out");
        Hashtable hashtable = new Hashtable(100_000_000);

        int n = in.nextInt();
        for (int i=0; i<n; i++) {
            int op = in.nextInt();
            long num = in.nextLong();
            switch (op) {
                case 1:
                    hashtable.put(num);
                    break;
                case 2:
                    hashtable.remove(num);
                    break;
                case 3:
                    int hasItem = hashtable.contains(num) ? 1 : 0;
                    out.write(String.format("%d\n", hasItem));
                    break;
            }
        }

        out.close();
        in.close();


//        int n = 2_000_000;
//        for (; !is_prime(n); n++);
//        System.out.println(n);
    }


}

class Hashtable {

    private LinkedList[] table;

    public Hashtable(int size) {
        for (; !is_prime(size); size++);
        table = new LinkedList[size];
    }

    void put(long item) {
        int hash = (int) item % table.length;
        if (table[hash] == null) {
            table[hash] = new LinkedList<Long>();
        }
        table[hash].add(item);
    }

    void remove(long item) {
        int hash = (int) item % table.length;
        if (table[hash] != null) {
            table[hash].remove(item);
        }
    }

    boolean contains(long item) {
        int hash = (int) item % table.length;
        if (table[hash] != null) {
            return table[hash].contains(item);
        }
        return false;
    }

    private boolean is_prime(int n) {
        if (n < 1) {
            throw new IllegalArgumentException("n should be a positive number");
        }
        if (n < 5) {
            return true;
        }
        int sqrtN = (int) Math.sqrt(n);
        for (int i = 2; i < sqrtN; i++) {
            if (n % i == 0) {
//                System.err.printf("%d %d\n", n, i);
                return false;
            }
        }
        return true;
    }

}