-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblem_10_3.py
More file actions
41 lines (36 loc) · 1.07 KB
/
Copy pathproblem_10_3.py
File metadata and controls
41 lines (36 loc) · 1.07 KB
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
INF = float('inf')
def tpath():
global adj, weights
adj = [{} for _ in range(n)]
for a,b,w in edges:
adj[a][b] = adj[b][a] = w
weights = {edges[i][2] for i in range(m)}
weights = sorted(list(weights))
return min_diff()
def min_diff():
ret = INF
for lo in range(len(weights)):
for hi in range(lo+1, len(weights)):
if has_path(weights[lo], weights[hi]):
ret = min(ret, weights[hi] - weights[lo])
break
return ret
def has_path(lo, hi):
global visited
visited = [False] * n
return dfs(0, lo, hi)
def dfs(here, lo, hi):
if here == n - 1:
return True
else:
visited[here] = True
for there, weight in adj[here].items():
if not visited[there] and (lo <= weight <= hi):
if dfs(there, lo, hi):
return True
return False
for _ in range(int(input())):
n, m = map(int, input().split())
edges = [list(map(int, input().split())) for _ in range(m)]
ret = tpath()
print(0 if ret == INF else ret)