Cod sursa(job #2378684)

Utilizator KemyKoTeo Virghi KemyKo Data 12 martie 2019 15:45:30
Problema Hashuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.21 kb
#include <fstream>
#include <set>

#define MOD 666667

using namespace std;

class InParser {
private:
	FILE *fin;
	char *buff;
	int sp;

	char read_ch() {
		++sp;
		if (sp == 4096) {
			sp = 0;
			fread(buff, 1, 4096, fin);
		}
		return buff[sp];
	}

public:
	InParser(const char* nume) {
		fin = fopen(nume, "r");
		buff = new char[4096]();
		sp = 4095;
	}

	InParser& operator >> (int &n) {
		char c;
		while (!isdigit(c = read_ch()) && c != '-');
		int sgn = 1;
		if (c == '-') {
			n = 0;
			sgn = -1;
		} else {
			n = c - '0';
		}
		while (isdigit(c = read_ch())) {
			n = 10 * n + c - '0';
		}
		n *= sgn;
		return *this;
	}

	InParser& operator >> (long long &n) {
		char c;
		n = 0;
		while (!isdigit(c = read_ch()) && c != '-');
		long long sgn = 1;
		if (c == '-') {
			n = 0;
			sgn = -1;
		} else {
			n = c - '0';
		}
		while (isdigit(c = read_ch())) {
			n = 10 * n + c - '0';
		}
		n *= sgn;
		return *this;
	}
};

InParser f("hashuri.in");
ofstream g("hashuri.out");

int n;
multiset <int> v[MOD + 1];

int getPos(int x)
{
    //Return hash value of x as the pos in the hash table
    unsigned int hs = 5381;

    while(x > 0){
        hs = ((hs << 5) + hs) + ((x % 10) + 33); /* hs * 33 + (x % 10) */
        x /= 10;
    }

    return hs % MOD;
}

bool searchElement(const int x)
{
    int pos = getPos(x);

    //Binary search in multiset (returns position where it finds x)
    multiset<int>::iterator const it = v[pos].lower_bound(x);

    //If x was found, return true
    return ((*it) == x);
}

void insertElement(const int x)
{
    int pos = getPos(x);

    if(!searchElement(x))
        v[pos].insert(x);
}

void deleteElement(int x)
{
    int pos = getPos(x);

    //Multiset search + deletion
    v[pos].erase(x);
}

int main()
{
    int i, op, x;
    f >> n;

    for(i=1; i<=n; ++i){
        f >> op >> x;
        switch(op){
            case 1:
                insertElement(x);
                break;
            case 2:
                deleteElement(x);
                break;
            case 3:
                g << searchElement(x) << '\n';
                break;
        }
    }

    return 0;
}