
* 겪고 있는 문제 상황을 최대한 자세하게 작성해주세요.
* 문제 해결을 위해 어떤 시도를 해보았는지 구체적으로 함께 알려주세요.
https://www.acmicpc.net/board/search/all/problem/6416/
웬만하면 스스로 찾아보려 노력하는데, 하루 종일 고민해도 모르겠네요.
이렇게 고민해서 처리했는데 16퍼 정도에서 틀렸다고 나옵니다. 어디가 잘못된걸까요?
import sys
input = sys.stdin.readline
edges = {}
cnt = 0
while True:
ipt = list(map(int, input().split()))
if(len(ipt) == 0): continue
if(ipt[0] < 0 and ipt[1] < 0):
break
if(cnt not in edges):
edges[cnt] = ipt
else:
if(ipt[-1] == 0 and ipt[-2] == 0):
edges[cnt].extend(ipt[:-2])
else:
edges[cnt].extend(ipt)
if(ipt[-1] == 0 and ipt[-2] == 0): cnt += 1
def bfs_queue(graph, que, visited, n):
que.append(n)
ret = True
if(n not in visited): visited[n] = 1
else : visited[n] += 1
if(visited[n] > 1):
ret = False
while que:
if(ret == False): break
n = que.pop(0)
if(n in graph):
for d in graph[n]:
if(d not in visited): visited[d] = 1
else : visited[d] += 1
if(visited[d] > 1):
ret = False
break
que.append(d)
return ret
for n in edges:
item = edges[n]
edge_ln = len(item) // 2
cursor = 0
visited = {}
roots = set()
receive = set()
flag = False
graph = {}
que = []
nodes = set()
for _ in range(edge_ln):
e = (item[cursor], item[cursor + 1])
nodes.add(e[0])
nodes.add(e[1])
if(e[0] not in roots): roots.add(e[0])
if(e[1] not in receive): receive.add(e[1])
if(e[0] not in graph):
graph[e[0]] = [e[1]]
else:
graph[e[0]].append(e[1])
if(e[1] not in graph):
graph[e[1]] = []
cursor += 2
roots = roots.difference(receive)
roots = list(roots)
# 루트가 1개가 잡히냐
if(len(roots) != 1): flag = False
else:
# BFS 방문시 visited가 1번 이상 있느냐 -> 경로가 유일한지, 입구가 하나인지
flag = bfs_queue(graph,que,visited,roots[0])
if(len(visited) != len(nodes)): flag = False
# 공집합도 트리임
if(len(roots) == 0 and visited == {}): flag = True
temp = n + 1
print(f'Case {temp} is a tree.' if flag else f'Case {temp} is not a tree.')
