Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ### Problem
- n, m = map(int, input().split(' '))
- graph = {}
- pairs = []
- for _ in range(m):
- x, y = map(int, input().split(' '))
- pairs.append((x, y))
- graph.setdefault(x, [])
- graph.setdefault(y, [])
- graph[x].append(y)
- graph[y].append(x)
- weights = [1] * (n + 1)
- visited = [False] * (n + 1)
- def dfs(node):
- if not visited[node]:
- visited[node] = True
- if len(graph[node]) == 1:
- return
- for out in graph[node]:
- if out == node:
- continue
- if not visited[out]:
- dfs(out)
- weights[node] += weights[out]
- dfs(1)
- for x, y in pairs:
- if weights[x] < weights[y]:
- print("Crossing edge {}-{} there are {} paths".format(x, y, weights[x] * (weights[1] - weights[x])))
- else:
- print("Crossing edge {}-{} there are {} paths".format(x, y, weights[y] * (weights[1] - weights[y])))
- ### Expected time complexity O(N) - in DFS, you visit each node once (O(N) since there are N nodes), there are N - 1 edges (iterating over pairs will yield O(N))
- ### Expected space complexity O(N) - weights is of size N, visited is of size N, pairs is of size N - 1, graph is of size 2 * (N - 1) => O(N)
- ### TEST CASES
- ##### Human Comprehensible - used to check whether the math is correct on computing paths
- 7 6
- 1 2
- 1 3
- 1 4
- 1 5
- 4 6
- 4 7
- ##### Big Test Case - used for figuring out if weights are properly computed
- 22 21
- 2 1
- 3 1
- 4 1
- 2 5
- 2 6
- 2 7
- 2 8
- 7 13
- 7 14
- 7 15
- 8 16
- 3 9
- 4 10
- 4 11
- 4 12
- 10 17
- 10 18
- 18 19
- 18 20
- 18 21
- 18 22
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement