Suhwanc

 

접두사를 찾는 문제로

 

트라이를 이용하여 간단하게 풀 수 있는 문제입니다.

 

트라이란? https://suhwanc.tistory.com/98

 

주어진 문자열들을 (0 ~ 9) 정렬한 후, 뒤에서 부터 트라이에 이 문자열이 있는지 find 하고

 

없으면 insert를 반복해 전화번호 목록의 일관성을 찾아내면 됩니다.

 

소스 코드

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
using namespace std;
 
int t; //test case
int n; //call number
const int NUMBER = 10// '0' ~ '9'
 
int toNumber(char ch) { return ch - '0'; }
 
struct TrieNode {
    TrieNode* children[NUMBER];
    bool terminal;
    //생성, 소멸자
    TrieNode() : terminal(false) {
        memset(children, 0sizeof(children));
    }
    ~TrieNode() {
        for (int i = 0; i < NUMBER; i++)
            if (children[i]) delete children[i];
    }
    //트라이에 번호 추가
    void insert(const char* key) {
        if (*key == 0) terminal = true;
        else {
            int next = toNumber(*key);
            if (children[next] == NULL)
                children[next] = new TrieNode();
            children[next]->insert(key + 1);
        }
    }
    //트라이에 번호 일치 확인
    TrieNode* find(const char* key) {
        if (*key == 0return this;
        int next = toNumber(*key);
        if (children[next] == NULLreturn NULL;
        return children[next]->find(key + 1);
    }
};
int main()
{
    ios_base::sync_with_stdio(0);
    cin.tie(0);
 
    cin >> t;
    while (t--) {
        cin >> n;
        vector<string>input; //전화번호 길이 순 정렬
        for (int i = 0; i < n; i++) {
            char buf[11];
            cin >> buf;
            input.push_back(buf);
        }
        sort(input.begin(), input.end());
 
        TrieNode* trie = new TrieNode();
        bool check = false;
        for (int i = 0; i < input.size(); i++) {
            TrieNode* node = trie->find(input[input.size() - 1 - i].c_str());
            if (node != NULL) check = true;
            trie->insert(input[input.size() - 1 - i].c_str());
        }
        if (check) cout << "NO\n";
        else cout << "YES\n";
    }
}
cs

 

 

개발환경 : Visual Studio 2019

지적, 조언 언제든지 환영입니다~~

'백준 문제풀이' 카테고리의 다른 글

백준 1086 박성원  (0) 2021.05.16
백준 1946번 신입사원  (0) 2020.08.05
백준 9252번 LCS 2  (0) 2020.02.12
백준 5582번 공통 부분 문자열  (0) 2020.02.12
백준 9251번 LCS  (0) 2020.02.12