Advertisement
Guest User

Untitled

a guest
Aug 1st, 2015
187
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.30 KB | None | 0 0
  1. Problem Statement
  2.  
  3. Atul is into graph theory, and he is learning about trees nowadays. He observed that the removal of an edge from a given tree T will result in the formation of two separate trees, T1 and T2.
  4.  
  5. Each vertex of the tree T is assigned a positive integer. Your task is to remove an edge, such that the Tree_diff of the resultant trees is minimized. Tree_diff is defined as the following:
  6.  
  7. F(T) = Sum of numbers written on each vertex of a tree T
  8. Tree_diff(T) = abs(F(T1) - F(T2))
  9.  
  10. Input Format:
  11. The first line will contain an integer N, i.e. the number of vertices in the tree.
  12. The next line will contain N integers separated by a single space, i.e. the values assigned to each of the vertices.
  13. The next N−1 lines contain a pair of integers eah, separated by a single space, that denote the edges of the tree.
  14. In the above input, the vertices are numbered from 1 to N.
  15.  
  16. Output Format:
  17. A single line containing the minimum value of Tree_diff.
  18.  
  19. Constraints:
  20. 3≤N≤105
  21. 1≤ number written on each vertex ≤1001
  22.  
  23. Sample Input:
  24. 6
  25. 100 200 100 500 100 600
  26. 1 2
  27. 2 3
  28. 2 5
  29. 4 5
  30. 5 6
  31.  
  32. Sample Output:
  33. 400
  34.  
  35. Explanation:
  36.  
  37. Originally, we can represent tree as
  38.  
  39. 1(100)
  40.  
  41. 2(200)
  42. /
  43. (100)5 3(100)
  44. /
  45. (500)4 6(600)
  46. Cutting the edge at 1 2 would result in Tree_diff = 1500-100 = 1400
  47. Cutting the edge at 2 3 would result in Tree_diff = 1500-100 = 1400
  48. Cutting the edge at 2 5 would result in Tree_diff = 1200-400 = 800
  49. Cutting the edge at 4 5 would result in Tree_diff = 1100-500 = 600
  50. Cutting the edge at 5 6 would result in Tree_diff = 1000-600 = 400
  51.  
  52. Hence, the answer is 400.
  53.  
  54. def find_sum(v, p):
  55. s = vertices[v-1]
  56. stack = [(v,p)]
  57. while stack:
  58. v,p = stack.pop()
  59. for e in adj_list[v]:
  60. if p != e:
  61. s += vertices[e-1]
  62. stack.append((e,v))
  63. return s
  64.  
  65. n = int(raw_input())
  66. vertices = map(int, raw_input().split())
  67. adj_list = {}
  68. edges = []
  69. total = sum(vertices)
  70. res = total
  71. for _ in xrange(n-1):
  72. u, v = map(int, raw_input().split())
  73. edges.append((u,v))
  74. if u not in adj_list:
  75. adj_list[u] = []
  76. if v not in adj_list:
  77. adj_list[v] = []
  78. adj_list[v].append(u)
  79. adj_list[u].append(v)
  80.  
  81. for u,v in edges:
  82. tmp = find_sum(u,v)
  83. res = min(res, abs(tmp-abs(total-tmp)))
  84. print res
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement