본문 바로가기

트리/트라이

전화번호 목록

https://www.acmicpc.net/problem/5052

 

5052번: 전화번호 목록

첫째 줄에 테스트 케이스의 개수 t가 주어진다. (1 ≤ t ≤ 50) 각 테스트 케이스의 첫째 줄에는 전화번호의 수 n이 주어진다. (1 ≤ n ≤ 10000) 다음 n개의 줄에는 목록에 포함되어 있는 전화번호가

www.acmicpc.net

트라이에 전화번호들을 다 넣고

find를 하는 과정중에

isEnd가 true라면 false 반환 -> "NO"

 

<소스 코드>

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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#include <iostream>
#include <string>
#include <vector>
 
using namespace std;
 
bool flag;
 
struct Node {
    Node* next[10];
    bool isEnd;
 
    Node()
    {
        isEnd = false;
        fill(next, next + 10, nullptr);
    }
 
    ~Node()
    {
        for (int i = 0; i < 10; i++)
            if (next[i])
                delete next[i];
    }
 
    void add(const string &str, int genzai)
    {
        if (genzai == str.length())
        {
            isEnd = true;
            return;
        }
        else
        {
            int idx = str[genzai] - '0';
 
            if (next[idx] == NULL)
            {
                next[idx] = new Node();
            }
            next[idx]->add(str, genzai + 1);
        }
    }
 
    bool find(const string& str, int genzai)
    {
        if (str[genzai] == '\0')
            return false;
 
        if (isEnd == true)
            return true;
 
        int idx = str[genzai] - '0';
        if (next[idx] == NULL)
            return false;
 
        return next[idx]->find(str, genzai + 1);
    }
 
};
 
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(NULL);
 
    int test;
    cin >> test;
 
    while (test--)
    {
        int n;
        cin >> n;
 
        Node root;
        vector<string> numbers(n);
        for (int i = 0; i < n; ++i)
            cin >> numbers[i];
 
        for (int i = 0; i < n; i++)
        {
            root.add(numbers[i], 0);
        }
 
        int i;
        for (i = 0; i < n; i++)
        {
            if (root.find(numbers[i], 0))
            {
                cout << "NO" << '\n';
                break;
            }
        }
 
        if(i == n)
            cout << "YES" << '\n';
    }
}
 
 
 
cs

'트리 > 트라이' 카테고리의 다른 글

휴대폰 자판  (0) 2024.03.14
단어 검색  (0) 2024.02.04
트라이 기초  (0) 2024.01.12