반응형
트라이 (Trie)
트라이 (Trie) 자료구조 트라이 자료구조는 문자열 검색을 빠르게 실행할 수 있도록 설계한 트리 형태의 자료구조입니다 - 트라이의 형태 -예시 코드 class Node { public: Node* childs[26]; bool isLeaf = false;
flrjtwjrjt.tistory.com
트라이 자료구조를 이용해서 빠르게 탐색하는 방식으로 구현하였음.
#include <iostream>
using namespace std;
static int N, M;
class Node
{
public:
Node* childs[26];
bool isLeaf = false;
Node()
{
fill(childs, childs + 26, nullptr);
}
void insert(const char* key)
{
if (*key == 0) {
isLeaf = true;
return;
}
int nextID = *key - 'a';
if (childs[nextID] == nullptr)
childs[nextID] = new Node();
childs[nextID]->insert(key + 1);
}
Node* find(const char* key)
{
if (*key == 0)
return this;
int nextID = *key - 'a';
if (childs[nextID] == nullptr)
return nullptr;
return childs[nextID]->find(key + 1);
}
};
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> N >> M;
Node* root = new Node();
while (N--)
{
char text[501];
cin >> text;
root->insert(text);
}
int count = 0;
while (M--)
{
char text[501];
cin >> text;
Node* node = root->find(text);
if (node && node->isLeaf)
count++;
}
cout << count << "\n";
}
반응형
LIST
'알고리즘 문제 > 백준' 카테고리의 다른 글
2024 구간 합 구하기 (세그먼트 트리) [Gold I] (0) | 2024.04.22 |
---|---|
1991 트리 순회 (트리 순회)[Silver I] (0) | 2024.04.21 |
13023 ABCDE (DFS) (0) | 2023.04.04 |
2023 신기한 소수 (0) | 2023.03.30 |
11724 연결 요소의 개수(BFS) (2) | 2023.03.14 |