728x90
๋ฐฑ์ค 14425: ๋ฌธ์์ด ์งํฉ
https://www.acmicpc.net/problem/14425
์ ๊ทผ ๋ฐฉํฅ ๋ฐ ๋๋ฒ๊น
ํธ๋ผ์ด ๊ตฌํ
- find ๋ฅผ ํ์ฉํ๋ฉด ํจ์ฌ ์๊ฐ๋ ๋น ๋ฅด๊ณ ๊ตฌํ๋ ๊ฐ๋จํ ๋ฌธ์ ์ด๋, ํธ๋ผ์ด ์๋ฃ๊ตฌ์กฐ๋ฅผ ํ์ตํ๋ ์ฐจ์์์ ํธ๋ผ์ด๋ก ๊ตฌํ
- ๊ฐ๋ณ ๋ ธ๋๋ฅผ ๋ด๋นํ struct ๋ฅผ ๊ตฌ์ฑํ๊ณ , ๋จ์ด๊ฐ ์ ๋ ฅ๋ ๋๋ง๋ค ๊ฐ ๊ธ์๋ฅผ ํธ๋ฆฌ ํํ๋ก ํ์ฑ
- ๋จ์ด๊ฐ ์งํฉ์ ์กด์ฌํ๋์ง ์ฐพ์ ๋๋ ๊ตฌ์ฑ๋ ํธ๋ฆฌ๋ฅผ ํ์
- ์ค์ํ ์ ์, ํธ๋ฆฌ๋ฅผ ๊ตฌ์ฑํ ๋ ๋จ์ด๊ฐ ๋๋๋ ์ง์ ์ ๋ช ํํ๊ฒ ํ์ํด์ฃผ์ด์ผ ๊ฒ์์ด ์ ํํ๊ฒ ๋๋ค๋ ์ !
์ฝ๋
/* 1091816KB 1680ms */
#include <iostream>
#include <stdio.h>
#include <string>
#include <cstring>
using namespace std;
struct trie {
int val;
trie * children[26];
trie() {
memset(children, NULL, sizeof(children));
//for (int i = 0; i < 26; i++) {
// children[i] = NULL;
//}
}
};
int main() {
freopen("input.txt", "r", stdin);
int N, M;
cin >> N >> M;
trie t = * new trie;
for (int i = 0; i < N; i++) {
string str;
cin >> str;
trie * tmp = &t;
for (int j = 0; j < str.size(); j++) {
int letter = (int)str[j] - 97;
if (tmp->children[letter] == NULL) {
tmp->children[letter] = new trie;
}
tmp = tmp->children[letter];
}
tmp->val = 1;
}
int cnt = 0;
for (int i = 0; i < M; i++) {
string str;
cin >> str;
bool flag = true;
trie * tmp = &t;
for (int j = 0; j < str.size(); j++) {
int letter = (int)str[j] - 97;
if (tmp->children[letter] == NULL) {
flag = false;
break;
}
tmp = tmp->children[letter];
}
if (flag && tmp->val) {
cnt++;
}
}
cout << cnt;
return 0;
}
๋ฐฐ์ด ์
- a ~ z ๋ฅผ 0 ~ 26 ์ ์๋ก ๋ณํํ๋ ๋ฐฉ๋ฒ์ผ๋ก๋ %97 ์ฐ์ฐ ์ธ์๋ (int)str - 97 ๋๋ (int)str - 'a' ๋ ๊ฐ๋ฅํ๋ค
'๐ป DEV > Algorithms & Data Structure' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[์๊ณ ๋ฆฌ์ฆ][C++] ์ธ๊ทธ๋จผํธ ํธ๋ฆฌ (0) | 2024.03.13 |
---|---|
[์๊ณ ๋ฆฌ์ฆ][C++] ์ฐ์ ์์ํ, ํํ (0) | 2024.03.11 |
[์๊ณ ๋ฆฌ์ฆ][C++] Dijkstra (๋ค์ต์คํธ๋ผ) / ์ต๋จ ๊ฒฝ๋ก ํ์ (0) | 2024.03.11 |
[Algorithms] ์๊ฐ๋ณต์ก๋ (Big-O Notation) ๋? (0) | 2021.07.08 |
[Data Structure] ์คํ(Stack) ๊ณผ ํ(Queue) (0) | 2021.07.07 |
๋๊ธ