백준 알고리즘/해시

[백준 알고리즘] 1920번 수 찾기 - C

개발로 먹고 살자 2021. 12. 3. 09:59

#include<stdio.h>
#include<stdlib.h>

#define BUCKET_SIZE 1000

struct bucket* hashTable = NULL;

struct node {
        int key;
        struct node* next;
};

struct bucket {
        struct node* head;
        int count;
};

int createHash(int key) {
        if(key < 0) {
                key *= -1;
        }

        return key % BUCKET_SIZE;
}

struct node* createNode(int key) {
        struct node* newNode = (struct node*)malloc(sizeof(struct node));

        newNode->key = key;
        newNode->next = NULL;

        return newNode;
}
void add(int key) {
        int hashIndex = createHash(key);

        struct node* newNode = createNode(key);

        if(hashTable[hashIndex].count == 0) {
                hashTable[hashIndex].count = 1;
                hashTable[hashIndex].head = newNode;
        } else {
                newNode->next = hashTable[hashIndex].head;
                hashTable[hashIndex].head = newNode;
                hashTable[hashIndex].count++;
        }
}

void search(int key) {
        int hashIndex = createHash(key);
        struct node* node = hashTable[hashIndex].head;
        int flag = 0;

        while(node != NULL) {
                if(node->key == key) {
                        flag = 1;
                        break;
                }
                node = node->next;
        }
        if(flag == 1) {
                printf("1\n");
        } else {
                printf("0\n");
        }
}
int main(int argc, char* argv[]) {
        hashTable = (struct bucket*)malloc(BUCKET_SIZE *sizeof(struct bucket));

        for(int i = 0; i < 2; i++) {
                int input;
                scanf("%d", &input);
                if(i == 0) {
                        for(int i = 0; i < input; i++) {
                                int value;
                                scanf("%d", &value);
                                add(value);
                        }
                } else {
                        for(int i = 0; i < input; i++) {
                                int value;
                                scanf("%d", &value);
                                search(value);
                        }
                }
        }


        return 0;
}