Advertisement
wrequiems

Untitled

Mar 9th, 2019
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.57 KB | None | 0 0
  1. ### Problem
  2. n, m = map(int, input().split(' '))
  3.  
  4. graph = {}
  5. pairs = []
  6. for _ in range(m):
  7.     x, y = map(int, input().split(' '))
  8.     pairs.append((x, y))
  9.     graph.setdefault(x, [])
  10.     graph.setdefault(y, [])
  11.     graph[x].append(y)
  12.     graph[y].append(x)
  13.  
  14. weights = [1] * (n + 1)
  15.  
  16. visited = [False] * (n + 1)
  17.  
  18. def dfs(node):
  19.     if not visited[node]:
  20.         visited[node] = True
  21.         if len(graph[node]) == 1:
  22.             return
  23.         for out in graph[node]:
  24.             if out == node:
  25.                 continue
  26.             if not visited[out]:
  27.                 dfs(out)
  28.                 weights[node] += weights[out]
  29.  
  30. dfs(1)
  31.  
  32. for x, y in pairs:
  33.     if weights[x] < weights[y]:
  34.         print("Crossing edge {}-{} there are {} paths".format(x, y, weights[x] * (weights[1] - weights[x])))
  35.     else:
  36.         print("Crossing edge {}-{} there are {} paths".format(x, y, weights[y] * (weights[1] - weights[y])))
  37.  
  38. ### 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))
  39. ### 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)
  40.  
  41. ### TEST CASES
  42. ##### Human Comprehensible - used to check whether the math is correct on computing paths
  43. 7 6
  44. 1 2
  45. 1 3
  46. 1 4
  47. 1 5
  48. 4 6
  49. 4 7
  50.  
  51. ##### Big Test Case - used for figuring out if weights are properly computed
  52. 22 21
  53. 2 1
  54. 3 1
  55. 4 1
  56. 2 5
  57. 2 6
  58. 2 7
  59. 2 8
  60. 7 13
  61. 7 14
  62. 7 15
  63. 8 16
  64. 3 9
  65. 4 10
  66. 4 11
  67. 4 12
  68. 10 17
  69. 10 18
  70. 18 19
  71. 18 20
  72. 18 21
  73. 18 22
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement