terrybrowser   1년 전

인접리스트로 하면 정답이 나오고 인접 행렬로 풀면 2% 진행하다가 틀리다고 나옵니다. 아무리 생각해도 두 코드의 차이가 없는 것 같은데 왜 틀리다고 나오는지 고수님들 의견 부탁 드립니다.

#######인접 리스트로 품 (정답) ########################
import sys
import heapq

input = sys.stdin.readline

N = int(input())
M = int(input())

data = [list(map(int,input().split())) for _ in range(M)]
S,D = map(int,input().split())



INF = int(1e9)


matrix = [[] for _ in range(N+1)]
distance = [INF]*(N+1)

for a,b,c in data:
matrix[a].append((b,c))


def bfs(s,d):
q = []
heapq.heappush(q,(0,s))
distance[s] = 0

while q:
dist,node = heapq.heappop(q)

if node == d:
return dist

for next_d,kuri in matrix[node]:
cost = dist+kuri

if cost < distance[next_d]:
heapq.heappush(q,(cost,next_d))
distance[next_d] = cost


rv = bfs(S,D)

print(rv)


###########인접행렬 (오답 발생) ###########################
import sys
import heapq

input = sys.stdin.readline

N = int(input())
M = int(input())

data = [list(map(int,input().split())) for _ in range(M)]
S,D = map(int,input().split())



INF = int(1e9)

matrix = [[INF]*(N+1) for _ in range(N+1)]

for a,b,c in data:
matrix[a][b] = c


def bfs(s,d):
distance = [INF]*(N+1)

q = []
heapq.heappush(q,(0,s))
distance[s] = 0

while q:
dist,node = heapq.heappop(q)

if node == d:
return dist

for next_d in range(1,N+1):
if matrix[node][next_d] == INF or next_d == node:
continue
cost = dist + matrix[node][next_d]

if cost < distance[next_d]:
heapq.heappush(q,(cost,next_d))
distance[next_d] = cost


rv = bfs(S,D)

print(rv)

lcr7324   1년 전

반례 드립니다.

해당 반례는 testcase.ac 서비스를 통하여 발견되었습니다.

추가로, 질문을 올릴 때 코드는 본문에 붙여 넣는 대신 "소스 코드" 란에 붙여 넣어주시면 코드의 양식이 그대로 유지되어 답변자가 답변하기 훨씬 수월해집니다.

다음에 질문을 올릴 때 참고 부탁드립니다.

terrybrowser   1년 전

감사합니다. 말씀 주신 반례로 오류를 발견할 수 있었습니다.

댓글을 작성하려면 로그인해야 합니다.