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 |
Tags
- 에라토스테네스의 체
- 투 포인터
- 완전탐색
- CS
- 위상정렬
- JUnit 5
- 문자열
- 시뮬레이션
- 그리디
- 프로그래머스
- 후니의 쉽게 쓴 시스코 네트워킹
- 수학
- mst
- 동적계획법
- 백준
- 백트래킹
- java
- 유니온 파인드
- 이분탐색
- 구현
- Kotlin
- 스택
- 알고리즘
- dfs
- 플로이드-와샬
- Network
- BFS
- Effective Java
- swea
- 세그먼트 트리
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 |