티스토리 뷰

https://www.acmicpc.net/problem/1620



숫자 -> 포켓몬 이름: 미리 저장해둔 문자열 순서로 찾는다.

포켓몬 이름 -> 숫자: 해시 테이블을 이용한다. 체이닝 방식을 사용했다.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#include <stdio.h>
#define MAX_DATA 25
#define MAX_TABLE 100007
#define MAX_POOL 200050
#define NULL 0
 
struct NODE
{
    int key;
    char data[MAX_DATA];
    NODE *next;
};
 
NODE hash_table[MAX_TABLE];
NODE pool[MAX_POOL];
int pool_cnt;
char name_table[MAX_POOL][MAX_DATA];
 
unsigned long hash_func(const char *str)
{
    unsigned long hash = 5381;
    int c;
 
    while(c = *str++)
        hash = (((hash << 5+ hash) + c) % MAX_TABLE;
 
    return hash % MAX_TABLE;
}
 
void strcpy(char *dest,char *src)
{
    for(int i=0; ;i++)
    {
        dest[i]=src[i];
        if(src[i]==NULL)
            break;
    }
}
 
int strcmp(char *s1,char *s2)
{
    for(int i=0; ;i++)
    {
        if(s1[i]!=s2[i])
            return 1;
        if(s1[i]==NULL && s2[i]==NULL)
            return 0;
    }
}
 
void add(int key,char *data)
{
    unsigned long h=hash_func(data);
 
    NODE *node=&pool[pool_cnt++];
    node->key=key;
    strcpy(node->data,data);
    node->next=hash_table[h].next;
    hash_table[h].next=node;
 
    strcpy(name_table[key],data);
}
 
int find_num(char *data)
{
    unsigned long h=hash_func(data);
 
    NODE *ptr=hash_table[h].next;
    while(strcmp(ptr->data,data))
        ptr=ptr->next;
 
    return ptr->key;
}
 
int stoi(char *s)
{
    int ret=0;
    for(int i=0; ;i++)
    {
        if(s[i]==NULL)
            break;
        ret*=10;
        ret+=s[i]-'0';
    }
    return ret;
}
 
int main()
{
    int n,m;
    scanf("%d %d",&n,&m);
 
    for(int i=1;i<=n;i++)
    {
        char name[MAX_DATA];
        scanf("%s",name);
        add(i,name);
    }
 
    while(m--)
    {
        char s[MAX_DATA];
        scanf("%s",s);
 
        if(s[0]>='A' && s[0]<='Z')
            printf("%d\n",find_num(s));
        else
            printf("%s\n",name_table[stoi(s)]);
    }
    
    return 0;
}
cs


'Algorithm > BOJ' 카테고리의 다른 글

11048 이동하기  (0) 2019.10.12
9536 여우는 어떻게 울지?  (0) 2019.09.26
1707 이분 그래프  (0) 2019.01.27
2606 바이러스  (0) 2019.01.27
14003 가장 긴 증가하는 부분 수열 5  (0) 2018.11.14
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday