[문제 링크]

 

5052번: 전화번호 목록

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

www.acmicpc.net


트라이 자료구조를 활용하는 문제였다.

우선 전화번호 목록을 트라이에 담으면서 전화번호의 끝자리인 노드를 체크하였다.

그다음, 완성된 트라이에서 전화번호를 검색하여 끝자리에 도달하기 전에 다른 전화번호의 끝자리인 노드에 방문하게 되는지 여부를 판단하여 입력받은 전화번호 목록이 일관성 있는 목록인지 아닌지를 알 수 있다.


#include <iostream>
#include <cstring>
#include <vector>
#include <string>
using namespace std;

const int NUMBER = 10;

class TrieNode {
	TrieNode* children[NUMBER];
	bool terminal;

public:
	TrieNode() : terminal(false) {
		memset(children, 0, sizeof(children));
	}
	~TrieNode() {
		for (int i = 0; i < NUMBER; i++)
			if (children[i] != 0) delete children[i];
	}

	void insert(string& key, int here) {
		if (here == key.size()) 
			terminal = true;
		else {
			int next = key[here] - '0';
			if (children[next] == NULL)
				children[next] = new TrieNode();

			children[next]->insert(key, here + 1);
		}
	}

	bool find(string& key, int here) {
		if (here == key.size()) return true;
		
		if (this->terminal)
			return false;

		int next = key[here] - '0';
		return children[next]->find(key, here + 1);
	}
};

int main(void) {
	cin.tie(0);
	ios_base::sync_with_stdio(0);

	int t;
	cin >> t;
	
	while (t--) {
		int n;
		cin >> n;

		vector<string> numberList(10001);
		TrieNode* trie = new TrieNode();

		for (int i = 0; i < n; i++) {
			string num;
			cin >> num;
			numberList[i] = num;
			trie->insert(num, 0);
		}

		bool flag = true;
		for (int i = 0; i < n; i++) {
			if (!trie->find(numberList[i], 0)) {
				cout << "NO" << '\n';
				flag = false;
				break;
			}
		}
		if (flag)
			cout << "YES" << '\n';

		delete trie;
	}
}

'알고리즘 > BOJ' 카테고리의 다른 글

백준 10826번: 피보나치 수 4  (0) 2021.10.21
백준 14226번: 이모티콘  (0) 2021.10.20
백준 17135번: 캐슬 디펜스  (0) 2021.10.18
백준 12865번: 평범한 배낭  (0) 2021.10.15
백준 1600번: 말이 되고픈 원숭이  (0) 2021.09.10

+ Recent posts