-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathThe Story of a Tree.py
54 lines (44 loc) · 1.26 KB
/
The Story of a Tree.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
import sys
from math import gcd
from collections import defaultdict
sys.setrecursionlimit(10**9)
def dfs1():
root = 1
seen = {root, }
stack = [root]
count = 0
while stack:
root = stack.pop()
for node in tree[root]:
if node not in seen:
seen.add(node)
count += (root, node) in guess # if root is parent of node
stack.append(node)
return count
def dfs2(cost, k):
root = 1
seen = {root,}
stack = [(root, cost)]
t_win = 0
while stack:
(root, cost) = stack.pop()
t_win += (cost >= k)
for node in tree[root]:
if node not in seen:
seen.add(node)
stack.append((node, cost - ((root, node) in guess) + ((node, root) in guess)))
return t_win
q = int(input().strip())
for a0 in range(q):
n = int(input().strip())
tree = defaultdict(list)
for a1 in range(n-1):
u,v = map(int, input().strip().split(' '))
tree[u].append(v)
tree[v].append(u)
g,k = map(int, input().strip().split(' '))
guess = {tuple(map(int, input().split())) for _ in range(g)}
cost = dfs1()
win = dfs2(cost, k)
g = gcd(win, n)
print("{0}/{1}".format(win//g, n//g))