Skip to content

Instantly share code, notes, and snippets.

@maehrm
Created November 13, 2023 13:44
Show Gist options
  • Save maehrm/0c92c35b7c4d0c9c0db575736033b5ec to your computer and use it in GitHub Desktop.
Save maehrm/0c92c35b7c4d0c9c0db575736033b5ec to your computer and use it in GitHub Desktop.
from itertools import permutations
N = int(input())
A = [list(map(int, input().split())) for _ in range(N)]
M = int(input())
friends = [[True for _ in range(N)] for _ in range(N)]
for _ in range(M):
x, y = map(lambda x: int(x) - 1, input().split())
friends[x][y] = False # x, yは仲が悪い
friends[y][x] = False
ans = float("inf")
for lst in permutations(range(N)):
sum = A[lst[0]][0]
for i in range(1, N):
if friends[lst[i - 1]][lst[i]] == False:
break
sum += A[lst[i]][i]
else:
ans = min(ans, sum)
print(-1 if ans == float("inf") else ans)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment