Recalling Early Days GP with Trees

  • + 0 comments
    import sys
    
    sys.setrecursionlimit(10000000)
    
    n, r = input().strip().split(' ')
    n, r = [int(n), int(r)]
    
    g = {}
    gv = {}
    edge = []
    
    for c in range(1, n):
        i, j = input().strip().split(' ')
        if i not in g.keys():
            g[i] = []
            gv[i] = 0
        if j not in g.keys():
            g[j] = []
            gv[j] = 0
    
        g[i].append(j)
        g[j].append(i)
    
    
    def find_path(graph, start, end, path=[]):
        path = path + [start]
        if start == end:
            return path
        if start not in graph.keys():
            return None
        for node in graph[start]:
            if node not in path:
                newpath = find_path(graph, node, end, path)
                if newpath: return newpath
        return None
    
    
    u, p = input().strip().split(' ')
    u, p = [int(u), int(p)]
    
    for c in range(u):
        i, j, x = input().strip().split(' ')
        i, j, x = [str(i), str(j), int(x)]
        path = find_path(g, i, j)
        for pa in path:
            gv[pa] = gv[pa] + x
            x *= r
    for c in range(p):
        i, j = input().strip().split(' ')
        path = find_path(g, i, j)
        s = 0
        for p in path:
            s += gv[p]
        print(s % 100711433)