반응형

   문제

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



하나의 문자열이 다른 문자열을 포함하고 있는 경우가 있는지를 묻는문제라고도 볼수

있다.트라이 구조를 통해 확인해보았다. 입력을 받는도중에 확인하는방법도 생각해 

보았지만 시간제한에 걸리지 않을거 같고 오류발생을 줄이기 위해

모든 문자열을 확인하는 방식으로 구현했다.



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
import sys
 
class Node:
    def __init__(self,data):
        self.data=data
        self.child=[None for _ in range(10)]
        self.check=False
 
class Trie:
    def __init__(self):
        self.root=Node('')
 
    def insert(self,phone):
        tmp=self.root
        for i in phone:
            if tmp.child[i] != None:#비어있지 않으면
                tmp=tmp.child[i]
            else:
                new=Node(i)
                tmp.child[i]=new
                tmp=new            
        tmp.check=True
        
 
    def consistency(self,phone):
        tmp=self.root
        for i in range(len(phone)):
            # print(tmp.check)
            if tmp.check:#다른문자열을 포함하고 있다면
                return False
            tmp=tmp.child[phone[i]]
        return True
 
 
for _ in range(int(input())):
    n=int(input())
    phone_list = []
    trie=Trie()
    for _ in range(n):
        phone=list(map(int,sys.stdin.readline().rstrip()))
        trie.insert(phone)
        phone_list.append(phone)
    result=True
    for p in phone_list:
        result*=trie.consistency(p)
 
    if result:
        print('YES')
    else:
        print('NO')
 
 

cs


반응형
  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기