Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 문자열
- 그리디
- 알고리즘
- 백트래킹
- 완전탐색
- 시뮬레이션
- 에라토스테네스의 체
- BFS
- java
- Effective Java
- 구현
- 이분탐색
- 스택
- 수학
- 프로그래머스
- 백준
- 세그먼트 트리
- 동적계획법
- dfs
- swea
- 위상정렬
- CS
- 유니온 파인드
- JUnit 5
- Kotlin
- mst
- 플로이드-와샬
- 투 포인터
- 후니의 쉽게 쓴 시스코 네트워킹
- Network
Archives
반갑습니다!
[백준] 5052 전화번호 목록 본문
풀이
Trie
자료구조를 사용하면 쉽게 해결할 수 있는 문제이다.
코드
#include <iostream>
#include <cstring>
using namespace std;
struct Trie {
bool end, has_child;
Trie* child[10];
Trie() {
end = false;
has_child = false;
fill(child, child + 10, nullptr);
}
~Trie() {
for (int i = 0; i < 10; i++)
if (child[i]) delete child[i];
}
void insert(const string& str, int idx) {
char key = str[idx];
if (key == '\0') end = true;
else {
int next = key - '0';
if (!child[next]) child[next] = new Trie;
has_child = true;
child[next]->insert(str, idx+1);
}
}
bool consistent() {
if (end && has_child) return false;
for (int i = 0; i < 10; i++)
if (child[i] && !child[i]->consistent()) return false;
return true;
}
};
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
Trie* root = new Trie;
while (n--) {
string num;
cin >> num;
root->insert(num, 0);
}
cout << (root->consistent() ? "YES\n" : "NO\n");
delete root;
}
}
'알고리즘 문제 풀이' 카테고리의 다른 글
[백준] 14425 문자열 집합 (0) | 2020.04.23 |
---|---|
[프로그래머스] 자동완성 (0) | 2020.04.23 |
[백준] 2234 성곽 (0) | 2020.04.22 |
[백준] 1600 말이 되고픈 원숭이 (0) | 2020.04.22 |
[백준] 1726 로봇 (0) | 2020.04.22 |