반응형
개념은 매우 간단하다. 여기보면 이해하기 쉬운편(PS관점에서 trie에 관한 다른 인사이트도 얻을 수 있다)
단어가 끝나는 지점에 마킹해야함에 유의
글자단위 Trie
아래는 내가 구현해본 Trie코드이며, 이 문제의 답안이기도 하다.
|
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
|
#include <bits/stdc++.h>
using namespace std;
#define REP(i,n) for(int i=0;i<(int)(n);i++)
struct trie {
struct node { map<char, node> child; bool end = false; };
node root;
node* insert(node* n, char c) {
auto& m = n->child;
if (m.count(c) == 0) m[c] = node();
return &m[c];
}
void insert(string s) {
node* n = &root;
int m = s.length();
for(int j=0;j<m;j++) n = insert(n, s[j]);
n->end = true;
}
node* find(node* n, char c) {
auto& m = n->child;
if (m.count(c) == 0) return NULL;
return &m[c];
}
bool find(string s) {
node* n = &root;
int m = s.length();
for (int j = 0; j < m; j++) {
n = find(n, s[j]);
if (n == NULL) return false;
}
return n->end;
}
};
int32_t main()
{
int N, M; cin >> N >> M;
trie t;
REP(i, N) {
string s; cin >> s;
t.insert(s);
}
int ans = 0;
REP(i, M) {
string s; cin >> s;
ans += t.find(s) ? 1 : 0;
}
cout << ans << '\n';
return 0;
}
|
cs |
단어단위 Trie
이건 응용인데 글자단위와 비슷한 개념으로 풀 수 있다. 이 문제 참조.
반응형
'Programming > Algorithm' 카테고리의 다른 글
| 공통조상(LCA, Lowest Common Ancestor) 알고리즘 (0) | 2020.04.29 |
|---|---|
| 위상정렬(Topological Sort) (0) | 2020.04.23 |
| KMP( Knuth, Morris, Prett) (0) | 2020.04.20 |
| 기하 (0) | 2020.04.19 |
| 포화이진트리(perfect binary tree), 완전이진트리 (2) | 2020.04.19 |
