-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtask2.py
More file actions
70 lines (49 loc) · 1.24 KB
/
task2.py
File metadata and controls
70 lines (49 loc) · 1.24 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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# O(ElogE)
# zawsze s == 0, t == 1
from checker import check
from collections import deque
def edges_to_list(E):
n = 0
for u, v, _ in E:
u -= 1 # korekcja indeksowania od 1
v -= 1
if u > n: n = u
if v > n: n = v
n += 1
G = [[] for _ in range(n)]
for u, v, w in E:
u -= 1
v -= 1
G[u].append((v, w))
G[v].append((u, w))
return G, n
def BFS(G, s, t, n, tmp_weight):
visited = [False] * n
Q = deque()
visited[s] = True
Q.append(s)
while len(Q) > 0:
u = Q.popleft()
for v, w in G[u]:
if not visited[v] and w >= tmp_weight: # tmp_weight - wybrana waga, którą staramy się zwiększać
visited[v] = True
Q.append(v)
return visited[t]
def binary_find_weight(G, n, E, s, t):
p, r = 0, len(E) - 1
last = 0
while p < r:
q = (p + r) // 2
w = E[q][2]
if BFS(G, s, t, n, w):
last = q
p = q + 1
else:
r = q - 1
return E[last][2]
def solution(E):
s, t = 0, 1
G, n = edges_to_list(E)
sorted_E = sorted(E, key = lambda x:x[2])
return binary_find_weight(G, n, sorted_E, s, t)
check(solution)