-
Notifications
You must be signed in to change notification settings - Fork 74
/
Copy pathfriend_suggestion.py
60 lines (47 loc) · 1.88 KB
/
friend_suggestion.py
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
#!/usr/bin/python3
import sys
import queue
class BiDij:
def __init__(self, n):
self.n = n # Number of nodes
self.inf = n*10**6 # All distances in the graph are smaller
self.d = [[self.inf]*n, [self.inf]*n] # Initialize distances for forward and backward searches
self.visited = [False]*n # visited[v] == True iff v was visited by forward or backward search
self.workset = [] # All the nodes visited by forward or backward search
def clear(self):
"""Reinitialize the data structures for the next query after the previous query."""
for v in self.workset:
self.d[0][v] = self.d[1][v] = self.inf
self.visited[v] = False
del self.workset[0:len(self.workset)]
def visit(self, q, side, v, dist):
"""
Try to relax the distance to node v from direction side by
value dist.
"""
# Implement this method yourself
pass
def query(self, adj, cost, s, t):
self.clear()
q = [queue.PriorityQueue(), queue.PriorityQueue()]
self.visit(q, 0, s, 0)
self.visit(q, 1, t, 0)
# Implement the rest of the algorithm yourself
return -1
def readl():
return map(int, sys.stdin.readline().split())
if __name__ == '__main__':
n, m = readl()
adj = [[[] for _ in range(n)], [[] for _ in range(n)]]
cost = [[[] for _ in range(n)], [[] for _ in range(n)]]
for e in range(m):
u, v, c = readl()
adj[0][u - 1].append(v - 1)
cost[0][u - 1].append(c)
adj[1][v - 1].append(u - 1)
cost[1][v - 1].append(c)
t, = readl()
bidij = BiDij(n)
for i in range(t):
s, t = readl()
print(bidij.query(adj, cost, s - 1, t - 1))