문제링크
https://www.acmicpc.net/problem/14425
풀이방법
해당 문제를 트라이 알고리즘을 공부하기 위한 목적으로 트라이 알고리즘을 이용하여 풀었다. 트라이 알고리즘이란 문자열을 효율적으로 처리하기 위한 트리 자료 구조이다.
트라이 알고리즘에 대해서 잘 몰라서 공부가 필요하면 아래 영상을 참고하자 문제에 대한 상세 풀이도 존재한다.
코드
#include <bits/stdc++.h>
using namespace std;
const int ROOT = 1;
int unused = 2;
const int MX = 10000 * 500 + 5; // 최대 등장 가능한 글자의 수
bool chk[MX];
int nxt[MX][26];
int c2i(char c){
return c - 'a';
}
void insert(string& s){
int cur = ROOT;
for(auto c : s){
if(nxt[cur][c2i(c)] == -1)
nxt[cur][c2i(c)] = unused++;
cur = nxt[cur][c2i(c)];
}
chk[cur] = true;
}
bool find(string& s){
int cur = ROOT;
for(auto c : s){
if(nxt[cur][c2i(c)] == -1)
return false;
cur = nxt[cur][c2i(c)];
}
return chk[cur];
}
int n, m;
int main(void){
ios::sync_with_stdio(0);
cin.tie(0);
for(int i = 0 ; i < MX; i++)
fill(nxt[i], nxt[i]+26, -1);
cin >> n >> m;
while(n--){
string s;
cin >> s;
insert(s);
}
int ans = 0;
while(m--){
string s;
cin >> s;
ans += find(s);
}
cout << ans;
}
'CS(Computer Science)지식 > [C++][코딩 테스트] 자료구조 및 알고리즘' 카테고리의 다른 글
[C++] 백준 1543번: 문서 검색 (0) | 2024.02.04 |
---|---|
[C++] 백준 5052번: 전화번호 목록 (0) | 2024.02.04 |
[C++] 백준 14426번: 접두사 찾기(Large) (0) | 2024.02.03 |
[C++] 백준 1786번: 찾기 (0) | 2024.02.03 |
백준 14938번: 서강그라운드 (C++) (0) | 2024.02.03 |