내 세상

[Algorithms] Hashtable / Probing / Hash Chaining / DJB2 본문

Coding/Algorithms

[Algorithms] Hashtable / Probing / Hash Chaining / DJB2

sga8 2021. 3. 12. 12:18
728x90
#define _CRT_SECURE_NO_WARNINGS
 
#include <stdio.h>
 
const int LM = 5e5 + 100;
const int MOD = 65537;
 
int strcmp(const char* a, const char *b){
    while (*a && *a == *b){
        a++;
        b++;
    }
    return *a - *b;
}
 
int bCnt;
struct Node {
    char id[14];
    int isLogin;
    Node* next;
    Node* alloc(Node* np){
        isLogin = 0, next = np;
        return this;
    }
}buf[LM], htab[MOD];
 
int N, cmd;
int memberCnt, loginCnt;
 
unsigned int djb2(char* s){
    unsigned int h = 5381;
    for (; *s; s++){
        h = (h * 33) + *s;
    }
    return h % MOD;
}
 
Node* probing(int hidx, char* s){
    Node* p = &htab[hidx];
    //p->next를 확인했음.
    for (; p->next; p = p->next){
        if (strcmp(p->next->id, s) == 0) return p;
    }
    return NULL;
}
int main()
{
    scanf("%d", &N);
    for (int i = 0; i < N; i++){
        scanf("%d %s", &cmd, buf[bCnt].id);
        int hidx = djb2(buf[bCnt].id);
        Node* p = probing(hidx, buf[bCnt].id);
        if (cmd == 1){ // 가입 여부
            printf("%d\n", p != NULL);
        }
        else if (cmd == 2){ // 로그인 여부
            printf("%d\n", p && p->next->isLogin);
        }
        else if (cmd == 3){
            if (p == NULL){
                htab[hidx].next = buf[bCnt++].alloc(htab[hidx].next);
                memberCnt++;
            }
            printf("%d\n", memberCnt);
        }
        else if (cmd == 4){ // 탈퇴
            if (p){ // 회원이라면
                if (p->next->isLogin == 1) loginCnt--;
                p->next = p->next->next;
                memberCnt--; 
            }
            printf("%d\n", memberCnt);
        }
        else if (cmd == 5){ // 로그인
            if (p){
                if (p->next->isLogin == 0) {
                    p->next->isLogin = 1;
                    loginCnt++;
                }
            }
            printf("%d\n", loginCnt);
        }
        else { // 로그아웃
            if (p){
                if (p->next->isLogin == 1){
                    p->next->isLogin = 0;
                    loginCnt--;
                }
            }
            printf("%d\n", loginCnt);
        }
    }
    return 0;
}
728x90