Problem:
 Score : 600 points    Problem Statement  We have a tree with N vertices numbered 1 to N .
The i -th edge in this tree connects Vertex a_i and Vertex b_i . Consider painting each of these edges white or black. There are 2^{N-1} such ways to paint the edges. Among them, how many satisfy all of the following M restrictions?   The i -th (1 \leq i \leq M) restriction is represented by two integers u_i and v_i , which mean that the path connecting Vertex u_i and Vertex v_i must contain at least one edge painted black.       Constraints   2 \leq N \leq 50  1 \leq a_i,b_i \leq N  The graph given in input is a tree.  1 \leq M \leq \min(20,\frac{N(N-1)}{2})  1 \leq u_i < v_i \leq N  If i \not= j , either u_i \not=u_j or v_i\not=v_j  All values in input are integers.         Input  Input is given from Standard Input in the following format:  N  a_1  b_1  :  a_{N-1}  b_{N-1}  M  u_1  v_1  :  u_M  v_M       Output  Print the number of ways to paint the edges that satisfy all of the M conditions.        Sample Input 1 3
1 2
2 3
1
1 3      Sample Output 1 3  The tree in this input is shown below:     All of the M restrictions will be satisfied if Edge 1 and 2 are respectively painted (white, black), (black, white), or (black, black), so the answer is 3 .       Sample Input 2 2
1 2
1
1 2      Sample Output 2 1  The tree in this input is shown below:     All of the M restrictions will be satisfied only if Edge 1 is painted black, so the answer is 1 .       Sample Input 3 5
1 2
3 2
3 4
5 3
3
1 3
2 4
2 5      Sample Output 3 9  The tree in this input is shown below:           Sample Input 4 8
1 2
2 3
4 3
2 5
6 3
6 7
8 6
5
2 7
3 5
1 6
2 8
7 8      Sample Output 4 62  The tree in this input is shown below:

Solution (Python):




class Tree():
    def __init__(self, n, l):

        self.n = n

        
        self.w = {}
        for i in range(n - 1):
            a, b, path = l[i]
            if a in self.w:
                self.w[a].append((b, path))
            else:
                self.w[a] = [(b, path)]
            if b in self.w:
                self.w[b].append((a, path))
            else:
                self.w[b] = [(a, path)]


    
    def make_parents_list(self, root):
        self.parents = {}
        que = []
        seen = {}
        for i in range(1, n + 1):
            seen[i] = 0
        self.parents[root] = (None, None)
        seen[root] = 1
        que.append(root)
        while len(que) != 0:
            node = que.pop()
            for k in range(len(self.w[node])):
                node_2, path_2 = self.w[node][k]
                if seen[node_2] == 0:
                    seen[node_2] = 1
                    que.append(node_2)
                    self.parents[node_2] = (node, path_2)
                else:
                    continue
        return self.parents


    
    def lca(self, root, u, v):
        ancestors = set()
        if self.parents is None:
            parents = self.make_parents_list(root)
        else:
            parents = self.parents
        parent = u

        while parent is not None:
            ancestors.add(parent)
            parent = parents[parent][0]

        node = v
        while node not in ancestors:
            node = parents[node][0]

        return node


n = int(input())
l = []
for i in range(n - 1):
    a, b = [int(_) for _ in input().split()]
    l.append((a, b, i))
tree = Tree(n, l)
seiyaku = []
parents = tree.make_parents_list(1)
m = int(input())
for i in range(m):
    u, v = [int(_) for _ in input().split()]
    parent_node = tree.lca(1, u, v)
    s = set()
    node = u
    while node != parent_node:
        s.add(parents[node][1])
        node = parents[node][0]
    node = v
    while node != parent_node:
        s.add(parents[node][1])
        node = parents[node][0]
    seiyaku.append(s)

ans = 2 ** (n - 1)
for i in range(1, 2 ** m):
    i_bin = format(i, '0' + str(m) + 'b')
    k = 0
    q = []
    for j in range(m):
        if i_bin[j] == '1':
            q.append(j)
            k += 1
        else:
            continue
    s = set()
    for x in q:
        s |= seiyaku[x]
    ans += (-1) ** k * 2 ** (n - 1 -len(s))
    
    
    
    
    
    
    
    
print(ans)

Solution (Python):
n = int(input())
adj = [[] for _ in range(n)]
adj_dict = dict()

for i in range(n - 1):
    a, b = [int(x) - 1 for x in input().split()]
    adj[a].append(b)
    adj[b].append(a)
    if a > b:
        adj_dict[(b, a)] = i
    else:
        adj_dict[(a, b)] = i

m = int(input())
uv = []
for _ in range(m):
    uv.append([int(x) - 1 for x in input().split()])

def dfs(p, v, dest):
    if v == dest:
        return [v]
    if p != -1 and len(adj[v]) == 1:
        return False
    for nv in adj[v]:
        if nv == p:
            continue
        ret = dfs(v, nv, dest)
        if ret:
            return ret + [v]
    return False

edgest = [0] * (2 ** m)
for i, (u, v) in enumerate(uv):
    ret = dfs(-1, u, v)
    for uu, vv in zip(ret, ret[1:]):
        if uu > vv:
            uu, vv = vv, uu
        if (uu, vv) in adj_dict:
            edgest[1 << i] |= (1 << adj_dict[(uu, vv)])

for i in range(1, 2 ** m):
    lsb = i & (-i)
    edgest[i] = edgest[i ^ lsb] | edgest[lsb]

dp = [0] * (2 ** m)
dp[0] = 1 << (n - 1)
ans = dp[0]
for i in range(1, 2 ** m):
    lsb = i & (-i)
    lim = bin(edgest[i] ^ edgest[i ^ lsb]).count('1')
    dp[i] = dp[i ^ lsb] >> lim
    if bin(i).count('1') % 2 == 0:
        ans += dp[i]
    else:
        ans -= dp[i]
print(ans)

Solution (Python):

import sys
input = sys.stdin.readline
 
n = int(input())
edge = [[] for _ in range(n)]
edge_dict = dict()
 
for i in range(n - 1):
    a, b = [int(item) - 1 for item in input().split()]
    edge[a].append(b)
    edge[b].append(a)
    if a > b:
        edge_dict[(b, a)] = i
    else:
        edge_dict[(a, b)] = i
 
m = int(input())
uv = []
for _ in range(m):
    uv.append([int(item) - 1 for item in input().split()])
 
def dfs(p, v, dest):
    if v == dest:
        return [v]
    if p != -1 and len(edge[v]) == 1:
        return False
    for nv in edge[v]:
        if nv == p:
            continue
        ret = dfs(v, nv, dest)
        if ret:
            return ret + [v]
    return False
 

edgest = [0] * 2**m
for i, (u, v) in enumerate(uv):
    ret = dfs(-1, u, v)
    for uu, vv in zip(ret, ret[1:]):
        if uu > vv:
            uu, vv = vv, uu
        if (uu, vv) in edge_dict:
            edgest[1 << i] |= (1 << edge_dict[(uu, vv)])
for i in range(1, 2**m):
    lsb = i & (-i)
    edgest[i] = edgest[i ^ lsb] | edgest[lsb]
 

dp = [0] * 2**m
dp[0] = 1 << (n - 1)
ans = dp[0]
for i in range(1, 2**m):
    lsb = i & (-i)
    limit_num = bin(edgest[i] ^ edgest[i ^ lsb]).count("1")
    dp[i] = dp[i ^ lsb] >> limit_num
    
    if bin(i).count("1") % 2 == 0:
        ans += dp[i]
    else:
        ans -= dp[i]
print(ans)

Solution (Python):

import sys
input = sys.stdin.readline
 
n = int(input())
edge = [[] for _ in range(n)]
edge_dict = dict()
 
for i in range(n - 1):
    a, b = [int(item) - 1 for item in input().split()]
    edge[a].append(b)
    edge[b].append(a)
    if a > b:
        edge_dict[(b, a)] = i
    else:
        edge_dict[(a, b)] = i
 
m = int(input())
uv = []
for _ in range(m):
    uv.append([int(item) - 1 for item in input().split()])
 
def dfs(p, v, dest):
    if v == dest:
        return [v]
    if p != -1 and len(edge[v]) == 1:
        return False
    for nv in edge[v]:
        if nv == p:
            continue
        ret = dfs(v, nv, dest)
        if ret:
            return ret + [v]
    return False
 

edgest = [0] * 2**m
for i, (u, v) in enumerate(uv):
    ret = dfs(-1, u, v)
    for uu, vv in zip(ret, ret[1:]):
        if uu > vv:
            uu, vv = vv, uu
        if (uu, vv) in edge_dict:
            edgest[1 << i] |= (1 << edge_dict[(uu, vv)])
for i in range(1, 2**m):
    lsb = i & (-i)
    edgest[i] = edgest[i ^ lsb] | edgest[lsb]
 

dp = [0] * 2**m
dp[0] = 1 << (n - 1)
ans = dp[0]
for i in range(1, 2**m):
    lsb = i & (-i)
    limit_num = bin(edgest[i] ^ edgest[i ^ lsb]).count("1")
    dp[i] = dp[i ^ lsb] >> limit_num
    
    if bin(i).count("1") % 2 == 0:
        ans += dp[i]
    else:
        ans -= dp[i]
print(ans)

Solution (Python):

import sys
input = sys.stdin.readline
 
n = int(input())
edge = [[] for _ in range(n)]
edge_dict = dict()
 
for i in range(n - 1):
    a, b = [int(item) - 1 for item in input().split()]
    edge[a].append(b)
    edge[b].append(a)
    if a > b:
        edge_dict[(b, a)] = i
    else:
        edge_dict[(a, b)] = i
 
m = int(input())
uv = []
for _ in range(m):
    uv.append([int(item) - 1 for item in input().split()])
 
def dfs(p, v, dest):
    if v == dest:
        return [v]
    if p != -1 and len(edge[v]) == 1:
        return False
    for nv in edge[v]:
        if nv == p:
            continue
        ret = dfs(v, nv, dest)
        if ret:
            return ret + [v]
    return False
 

target_edge = [0] * m
for i, (u, v) in enumerate(uv):
    ret = dfs(-1, u, v)
    for uu, vv in zip(ret, ret[1:]):
        if uu > vv:
            uu, vv = vv, uu
        if (uu, vv) in edge_dict:
            target_edge[i] |= (1 << edge_dict[(uu, vv)])


edgest = [0] * 2**m
for i in range(1, 2**m):
    lsb = i & (-i)
    edgest[i] = edgest[i ^ lsb] | target_edge[lsb.bit_length() - 1]
 

dp = [0] * 2**m
dp[0] = 1 << (n - 1)
ans = dp[0]
for i in range(1, 2**m):
    lsb = i & (-i)
    n_edgest = edgest[i]
    p_edgest = edgest[i ^ lsb]
    limit_num = bin(n_edgest ^ p_edgest).count("1")
    dp[i] = dp[i ^ lsb] >> limit_num
    if bin(i).count("1") % 2 == 0:
        ans += dp[i]
    else:
        ans -= dp[i]
print(ans)

Solution (Python):

import sys
input = sys.stdin.readline
 
n = int(input())
edge = [[] for _ in range(n)]
edge_dict = dict()
 
for i in range(n - 1):
    a, b = [int(item) - 1 for item in input().split()]
    edge[a].append(b)
    edge[b].append(a)
    if a > b:
        edge_dict[(b, a)] = i
    else:
        edge_dict[(a, b)] = i
 
m = int(input())
uv = []
for _ in range(m):
    uv.append([int(item) - 1 for item in input().split()])
 
def dfs(p, v, dest):
    if v == dest:
        return [v]
    if p != -1 and len(edge[v]) == 1:
        return False
    for nv in edge[v]:
        if nv == p:
            continue
        ret = dfs(v, nv, dest)
        if ret:
            return ret + [v]
    return False
 

target_edge = [0] * m
for i, (u, v) in enumerate(uv):
    ret = dfs(-1, u, v)
    for uu, vv in zip(ret, ret[1:]):
        if uu > vv:
            uu, vv = vv, uu
        if (uu, vv) in edge_dict:
            target_edge[i] |= (1 << edge_dict[(uu, vv)])


edgest = [0] * 2**m
for i in range(1, 2**m):
    lsb = i & (-i)
    edgest[i] = edgest[i ^ lsb] | target_edge[lsb.bit_length() - 1]
 

dp = [0] * 2**m
dp[0] = 1 << (n - 1)
ans = dp[0]
for i in range(1, 2**m):
    lsb = i & (-i)
    n_edgest = edgest[i]
    p_edgest = edgest[i ^ lsb]
    limit_num = bin(n_edgest ^ p_edgest).count("1")
    dp[i] = dp[i ^ lsb] >> limit_num
    if bin(i).count("1") % 2 == 0:
        ans += dp[i]
    else:
        ans -= dp[i]
print(ans)

Solution (Python):

import sys
input = sys.stdin.readline
 
n = int(input())
edge = [[] for _ in range(n)]
edge_dict = dict()
 
for i in range(n - 1):
    a, b = [int(item) - 1 for item in input().split()]
    edge[a].append(b)
    edge[b].append(a)
    if a > b:
        edge_dict[(b, a)] = i
    else:
        edge_dict[(a, b)] = i
 
m = int(input())
uv = []
for _ in range(m):
    uv.append([int(item) - 1 for item in input().split()])
 
def dfs(p, v, dest):
    if v == dest:
        return [v]
    if p != -1 and len(edge[v]) == 1:
        return False
    for nv in edge[v]:
        if nv == p:
            continue
        ret = dfs(v, nv, dest)
        if ret:
            return ret + [v]
    return False
 
target_edge = [0] * m
for i, (u, v) in enumerate(uv):
    ret = dfs(-1, u, v)
    for uu, vv in zip(ret, ret[1:]):
        if uu > vv:
            uu, vv = vv, uu
        if (uu, vv) in edge_dict:
            target_edge[i] |= (1 << edge_dict[(uu, vv)])

edge_of_state = [0] * 2**m
for i in range(1, 2**m):
    lsb = i & (-i)
    edge_of_state[i] = edge_of_state[i ^ lsb] | target_edge[lsb.bit_length() - 1]
 

dp = [0] * 2**m
dp[0] = pow(2, n-1) 
ans = dp[0]
for i in range(1, 2**m):
    lsb = i & (-i)
    n_edgest = edge_of_state[i]
    p_edgest = edge_of_state[i ^ lsb]
    limit_num = bin(n_edgest ^ p_edgest).count("1")
    dp[i] = dp[i ^ lsb] // pow(2, limit_num)
    if bin(i).count("1") % 2 == 0:
        ans += dp[i]
    else:
        ans -= dp[i]
print(ans)

Solution (Python):
import sys
readline = sys.stdin.readline
popcntsum = ((1<<64) - 1)
Fa = [0] + [popcntsum//((1<<(1<<(i-1)))+1) for i in range(1,7)]
Fb = [0] + [Fa[i]<<(1<<(i-1)) for i in range(1,7)]
fila1 = Fa[1]
filb1 = Fb[1]
fila2 = Fa[2]
filb2 = Fb[2]
fila3 = Fa[3]
filb3 = Fb[3]
fila4 = Fa[4]
filb4 = Fb[4]
fila5 = Fa[5]
filb5 = Fb[5]
fila6 = Fa[6]
filb6 = Fb[6]
def popcount(x):
    x = (x&fila1) + ((x&filb1)>>1)
    x = (x&fila2) + ((x&filb2)>>2)
    x = (x&fila3) + ((x&filb3)>>4)
    x = (x&fila4) + ((x&filb4)>>8)
    x = (x&fila5) + ((x&filb5)>>16)
    x = (x&fila6) + ((x&filb6)>>32)
    return x

def parorder(Edge, p):
    N = len(Edge)
    par = [0]*N
    par[p] = -1
    stack = [p]
    order = []
    Enum = [None]*N
    visited = set([p])
    ast = stack.append
    apo = order.append
    while stack:
        vn = stack.pop()
        apo(vn)
        for vf, num in Edge[vn]:
            if vf in visited:
                continue
            visited.add(vf)
            par[vf] = vn
            Enum[vf] = num
            ast(vf)
    return par, order, Enum

def getcld(p):
    res = [[] for _ in range(len(p))]
    for i, v in enumerate(p[1:], 1):
        res[v].append(i)
    return res


N = int(readline())
Edge = [[] for _ in range(N)]
for i in range(N-1):
    a, b = map(int, readline().split())
    a -= 1
    b -= 1
    Edge[a].append((b, i))
    Edge[b].append((a, i))

root = 0
P, L, Enum = parorder(Edge, root)


M = int(readline())
Q = [tuple(map(int, readline().split())) for _ in range(M)]

dp = [0]*(1<<M)
ans = pow(2, N-1)
for S in range(1, 1<<M):
    pc = popcount(S)
    if pc == 1:
        i = (-S&S).bit_length() - 1
        table = [False]*(N-1)
        u, v = Q[i]
        u -= 1
        v -= 1
        while u != root:
            table[Enum[u]] = not table[Enum[u]]
            u = P[u]
        while v != root:
            table[Enum[v]] = not table[Enum[v]]
            v = P[v]
        res = 0
        for t in table:
            res <<= 1
            res |= t
        dp[S] = res
    else:
        dp[S] = dp[S^(-S&S)]|dp[-S&S]
    
    ans += (-1)**(pc%2)*pow(2, N-1-popcount(dp[S]))
print(ans)

Solution (Python):
N = int(input())
X = [[] for i in range(N)]
for i in range(N-1):
    x, y = map(int, input().split())
    X[x-1].append(y-1)
    X[y-1].append(x-1)

P = [-1] * N
DE = [0] * N
Q = [0]
while Q:
    i = Q.pop()
    for a in X[i][::-1]:
        if a != P[i]:
            P[a] = i
            DE[a] = DE[i] + 1
            X[a].remove(i)
            Q.append(a)

def lp(u, v):
    t = 0
    while u != v:
        if DE[u] > DE[v]:
            t += 1 << u-1
            u = P[u]
        elif DE[u] < DE[v]:
            t += 1 << v-1
            v = P[v]
        else:
            t += 1 << u-1
            t += 1 << v-1
            u = P[u]
            v = P[v]
    
    return t

Y = []
M = int(input())
for _ in range(M):
    a, b = map(int, input().split())
    a, b = a-1, b-1
    Y.append(lp(a, b))

def popcnt(n):
    c = (n & 0x5555555555555555) + ((n>>1) & 0x5555555555555555)
    c = (c & 0x3333333333333333) + ((c>>2) & 0x3333333333333333)
    c = (c & 0x0f0f0f0f0f0f0f0f) + ((c>>4) & 0x0f0f0f0f0f0f0f0f)
    c = (c & 0x00ff00ff00ff00ff) + ((c>>8) & 0x00ff00ff00ff00ff)
    c = (c & 0x0000ffff0000ffff) + ((c>>16) & 0x0000ffff0000ffff)
    c = (c & 0x00000000ffffffff) + ((c>>32) & 0x00000000ffffffff)
    return c

D = {1<<i: i for i in range(50)}
Z = [0] * (1<<M)
ans = 0
CC = [0] * N
for m in range(1<<M):
    a = m & (-m)
    if a == m:
        if a == 0:
            Z[m] = 0
        else:
            Z[m] = Y[D[a]]
    else:
        Z[m] = Z[m^a] | Y[D[a]]
    
    CC[N - 1 - popcnt(Z[m])] += (1 if popcnt(m) & 1 == 0 else -1)

print(sum([2 ** i * CC[i] for i in range(N)]))

Solution (Python):
import sys
input = sys.stdin.readline

N = int(input())
graph = [[] for _ in range(N)]
Edges = [[None]*N for _ in range(N)]
for i in range(N-1):
    a, b = map(int, input().split())
    graph[a-1].append(b-1)
    graph[b-1].append(a-1)
    Edges[a-1][b-1] = i
    Edges[b-1][a-1] = i

def dfs(p, L, checked, goal):
    if p == goal:
        return L
    checked[p] = True
    ok = False
    for np in graph[p]:
        if not checked[np]:
            L.append(np)
            retL = dfs(np, L, checked, goal)
            if retL:
                ok = True
                break
            L.pop()
    if ok:
        return retL
    else:
        return []


M = int(input())
Compression = []
for _ in range(M):
    a, b = map(int, input().split())
    a -= 1; b -= 1
    path = dfs(a, [], [False]*N, b)
    bit = 0
    pre = a
    for p in path:
        bit += 1<<Edges[pre][p]
        pre = p
    Compression.append(bit)

ans = 0
for bitmask in range(1,1<<M):
    whitebit = 0
    for i in range(M):
        if (1<<i)&bitmask:
            whitebit |= Compression[i]
    
    p = 1
    for n in range(M):
        if bitmask&(1<<n):
            p ^= 1
    E = 1
    for m in range(N-1):
        if whitebit&(1<<m) == 0:
            E *= 2
    
    ans += E*(-1)**p

print(2**(N-1)-ans)

Solution (Python):
import sys
from collections import defaultdict
readline = sys.stdin.readline
N, = map(int, readline().split())
def con(ll,E):
    r = 0
    for u, v in zip(ll,ll[1:]):
        u, v = sorted([u,v])
        r += 1<<E[(u,v)]
    return r

def process():
    G = [[] for _ in range(N+1)]
    E = dict()
    for i in range(N-1):
        a, b = sorted(map(int, readline().split()))
        G[a].append(b)
        G[b].append(a)
        E[(a,b)] = i

    M, = map(int, readline().split())
    qes = dict()
    for _ in range(M):
        u, v = sorted(map(int, readline().split()))
        if u not in qes:
            qes[u] = list()
        qes[u].append(v)
    dep = []
    for i in qes:
        ms = qes[i]
        path = []
        stack = [i]
        vs = set([i])
        while stack:
            v = stack.pop()
            if v > 0:
                vs.add(v)

                path.append(v)
                for u in G[v]:
                    if u in vs:
                        continue
                    if u in ms:
                        dep.append(con(path+[u],E))
                    stack += [-v, u]
            else:
                path.pop()
    r = 0
    for i in range(1,2**M):
        t = 0
        ns = 0

        for j in range(M):
            if i % 2:
                ns = ns | dep[j]
                t += 1
            i = i>>1
        xx = (1 if t%2 else -1)*2**(N-1-bin(ns).count("1"))
        r += xx
    print(2**(N-1)-r)
if __name__ == '__main__':
    process()

Solution (Python):


n = int(input())

TE = [[] for _ in range(n)]
TE2 = []
for i in range(n-1):
    ai,bi = map(int, input().split( ))
    ai -= 1
    bi -= 1
    TE[ai].append(bi)
    TE[bi].append(ai)
    TE2.append((ai,bi))
m  = int(input())
D =[]
for i in range(m):
    ai,bi = map(int ,input().split( ))
    ai -= 1
    bi-=1
    D.append((ai,bi))

bit = 1<<m


P =[0]*n
C = [[] for _ in range(n)]
from collections import deque
Q = deque()
Q.append(0)
V = [0]*n
V[0] = 1

while Q:
    v = Q.popleft()
    for u in TE[v]:
        if not V[u]:
            V[u] = 1
            Q.append(u)
            P[u] = v
            C[v].append(u)
def path(u,v):
    u_p = set()
    tmp1 = u
    while tmp1:
        u_p.add(tmp1)
        tmp1 = P[tmp1]
    u_p.add(tmp1)
    tmp2 = v

    while tmp2 not in u_p:
        tmp2 = P[tmp2]
    pth = 0
    tmp3 = u
    tmp4 = v
    while tmp3!=tmp2:
        for t in range(n-1):
            if TE2[t] == (tmp3,P[tmp3]) or TE2[t]==(P[tmp3],tmp3):
                pth |= (1<<t)
        tmp3 = P[tmp3]

    while tmp4!= tmp2:
        for t in range(n-1):
            if TE2[t] == (tmp4,P[tmp4]) or TE2[t]==(P[tmp4],tmp4):
                pth |= (1<<t)
        tmp4 = P[tmp4]
    return pth

D2 = [path(D[i][0],D[i][1]) for i in range(m)]

ans = 2**(n-1)
for i in range(1,bit):
    cnt = 0
    paths = 0
    for j in range(m):
        if (i>>j)&1:
            paths |= D2[j]
            cnt += 1
    cnt2 = 0
    for j in range(n-1):
        cnt2 += (paths>>j)&1
    ans += (-1)**cnt *2**(n-1-cnt2)
print(ans)

Solution (Python):

from collections import defaultdict,deque
from heapq import heappush, heappop
from itertools import permutations
import sys
import math
import bisect
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res
def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007

def solve():
    def dijkstra(s):
        d = [float("inf")]*n
        p = [s]*n
        d[s] = 0
        q = [(0,s)]
        while q:
            dx,x = heappop(q)
            nd = dx+1
            for y in v[x]:
                if nd < d[y]:
                    d[y] = nd
                    p[y] = x
                    heappush(q,(nd,y))
        path = [[i] for i in range(n)]
        for i in range(1,n):
            pre = path[i][-1]
            while pre != s:
                path[i].append(p[pre])
                pre = path[i][-1]
            path[i] = path[i][::-1]
        return d,path

    n = I()
    v = [[] for i in range(n)]
    e = defaultdict(lambda : 0)
    for i in range(n-1):
        a,b = LI()
        a -= 1
        b -= 1
        v[a].append(b)
        v[b].append(a)
        e[(a,b)] = i
        e[(b,a)] = i
    d = [[0]*n for i in range(n)]
    path = [[None]*n for i in range(n)]
    for i in range(n):
        D,p = dijkstra(i)
        d[i] = [j for j in D]
        path[i] = [j for j in p]
    m = I()
    l = LIR(m)
    for i in range(m):
        l[i][0] -= 1
        l[i][1] -= 1
    ans = 0
    B = [0]*m
    for j in range(m):
        x,y = l[j]
        for k in range(len(path[x][y])-1):
            a,b = path[x][y][k],path[x][y][k+1]
            B[j] |= 1<<e[(a,b)]
    for b in range(1,1<<m):
        f = bin(b).count("1")
        p = 0
        for j in range(m):
            if b&(1<<j):
                p |= B[j]
        s = bin(p).count("1")
        f &= 1
        k = 1<<(n-s-1)
        if f:
            ans += k
        else:
            ans -= k
    print((1<<(n-1))-ans)
    return


if __name__ == "__main__":
    solve()

Solution (Python):
from collections import defaultdict
from heapq import heappop, heappush


class Graph(object):

    def __init__(self):
        self.graph = defaultdict(list)

    def __len__(self):
        return len(self.graph)

    def add_edge(self, From, To, cost=1):
        self.graph[From].append((To,cost))

    def get_nodes(self):
        return self.graph.keys()
class Dijkstra(object):

    def __init__(self, graph, start):
        self.g = graph.graph
        self.dist = defaultdict(lambda:float('inf'))
        self.dist[start] = 0
        self.prev = defaultdict(lambda: None)
        self.Q = []
        heappush(self.Q,(self.dist[start], start))

        while  self.Q:
            dist_u, u = heappop(self.Q)
            if self.dist[u] < dist_u:
                continue
            for v, cost in self.g[u]:
                alt = dist_u + cost
                if self.dist[v] > alt:
                    self.dist[v] = alt
                    self.prev[v] = u
                    heappush(self.Q,(alt, v))

    def shortest_distance(self, goal):
        return self.dist[goal]

    def shortest_path(self, goal):
        path = []
        node = goal
        while node is not None:
            path.append(node)
            node = self.prev[node]

        return path[::-1]


N = int(input())
g = Graph()
d = {}
for i in range(N-1):
    a,b = map(int,input().split())
    a -= 1
    b -= 1
    d[(min(a,b),max(a,b))] = i
    g.add_edge(a,b)
    g.add_edge(b,a)

M = int(input())
l = [0]*M
for i in range(M):
    u,v = map(int,input().split())
    u -= 1
    v -= 1
    dij = Dijkstra(g,u)
    path = dij.shortest_path(v)
    for j in range(len(path)-1):
        a,b = path[j],path[j+1]
        l[i] += 2**d[(min(a,b),max(a,b))]

c = [0]*(M+1)
p2 = [2**i for i in range(50)]
for n in range(2**M):
    cnt = 0
    x = 0
    for i in range(M):
        if n&p2[i]==p2[i]:
            cnt += 1
            x |= l[i]
    y = 0
    for i in range(N-1):
        if x&p2[i]==p2[i]:
            y += 1
    c[cnt] += p2[N-1-y]

ans = 0
for i in range(M+1):
    if i%2==0:
        ans += c[i]
    else:
        ans -= c[i]

print(ans)

Solution (Python):
'''
包除原理
すべての条件を満たしている
2^{N-1}から「どれかの条件を満たしていない」を引けば良い
i番目の条件を満たしていない確率はかんたんに計算できる
Sに属していいないやつが全て条件を満たしていない確率については
Sに対応する辺が全て白となる確率を考えれば良い
'''
from collections import deque
N=int(input())
G=[[] for i in range(N)]
a=[0 for i in range(N-1)]
b=[0 for i in range(N-1)]
edges=dict()
for i in range(N-1):
    a[i],b[i]=map(int,input().split())
    a[i]-=1;b[i]-=1
    G[a[i]].append(b[i])
    G[b[i]].append(a[i])
    edges[(min(a[i],b[i]),max(a[i],b[i]))]=i
M=int(input())
u=[0 for i in range(M)]
v=[0 for i in range(M)]
for i in range(M):
    u[i],v[i]=map(int,input().split())
    u[i]-=1;v[i]-=1
root=[0 for i in range(M)]
for i in range(M):
    q=deque([u[i]])
    parents=[-1 for i in range(N)]
    reached=[0 for i in range(N)]
    while(len(q)>0):
        r=q.popleft()
        reached[r]=1
        for p in G[r]:
            if reached[p]==1:
                continue
            parents[p]=r
            q.append(p)
    x=v[i]
    while(1):
        if parents[x]==-1:
            break
        s=min(x,parents[x])
        t=max(x,parents[x])
        root[i]+=2**edges[(s,t)]
        x=parents[x]
ans=0
def cnt(x):
    ans=0
    for i in range(M):
        if x|(2**i)==x:
            ans+=1
    return ans
q=deque([])
q.append(0)
S=[0 for i in range(2**M)]
reached=[0 for i in range(2**M)]
while(len(q)>0):
    i=q.popleft()
    for j in range(M):
        if i&(2**j)==0:
            S[i|(2**j)]=S[i]|root[j]
            if reached[i|(2**j)]==0:
                q.append(i|(2**j))
                reached[i|(2**j)]=1
    ans+=(-1)**(cnt(i))*2**(N-bin(S[i]).count("1")-1)
print(ans)

Solution (Python):
N = int(input())
ab = [list(map(int, input().split())) for _ in range(N - 1)]
M = int(input())
uv = [list(map(int, input().split())) for _ in range(M)]

class Tree:
  C, RL = {}, {}
  R, N, D, S, P = None, None, None, None, None
  def __init__(s, num):
    s.N = num
  def set(s, a, b):
    if a in s.C: s.C[a].append(b)
    else: s.C[a] = [b]
    if b in s.C: s.C[b].append(a)
    else: s.C[b] = [a]
  def dfs(s, x, y, r):
    if x == y:
      return [x]
    for i in s.C[x]:
      if i != r:
        t = s.dfs(i, y, x)
        if t != False:
          return [x] + t
    return False

T = Tree(N)
for a, b in ab:
  a -= 1
  b -= 1
  T.set(a, b)

D = [[-1] * N for _ in range(N)]
for i in range(N - 1):
  a, b = ab[i][0] - 1, ab[i][1] - 1
  a, b = min(a, b), max(a, b)
  D[a][b] = i

NL = [[] for _ in range(M)]
for i in range(M):
  x, y, r = uv[i][0] - 1, uv[i][1] - 1, uv[i][0] - 1
  L = T.dfs(x, y, r)
  n = L[0]
  t = 0
  for j in range(1, len(L)):
    m = L[j]
    x, y = min(n, m), max(n, m)
    t = t | (1 << D[x][y])
    n = m
  NL[i] = t
  

ans = 1 << (N - 1)
c = 0
for i in range(1, 1 << M):
  t = i
  f = 0
  k = 0
  for j in range(M):
    if t & 1:
      f += 1
      k = k | NL[j]
    t >>= 1
  cnt = bin(k).count("1")
  if f % 2 == 1:
    c += pow(2, (N - 1 - cnt))
  else:
    c -= pow(2, (N - 1 - cnt))
print(ans - c)

Solution (Python):
from itertools import combinations

N = int(input())

adj = [list() for _ in range(N)]
for _ in range(N-1):
    a,b = map(int,input().split())
    adj[a-1].append(b-1)
    adj[b-1].append(a-1)

parent = [None]*N
visited = [False]*N
visited[0] = True
def rec(u):
    for v in adj[u]:
        if not visited[v]:
            parent[v] = u
            visited[v] = True
            rec(v)
rec(0)
del adj

M = int(input())



tasks = []

for q in range(M):
    u,v = map(int,input().split())
    u,v = u-1,v-1
    u2r = []
    v2r = []
    while u is not None:
        u2r.append(u)
        u = parent[u]
    while v is not None:
        v2r.append(v)
        v = parent[v]
    
    for i,(a,b) in enumerate(zip(reversed(u2r), reversed(v2r))):
        if a != b:
            break
    else:
        i += 1
    
    tasks.append(u2r[:-i]+v2r[:-i])

cnt = 0
sign = 1

for n in range(1,M+1):
    sub = 0
    for p in combinations(range(M),n):
        sub += 2**(N-1-len(set().union(*(tasks[i] for i in p))))
    cnt += sign*sub
    sign *= -1
print(2**(N-1)-cnt)

Solution (Python):
def main():
    from itertools import combinations
    n = int(input())
    ab = [tuple(sorted(list(map(int, input().split())))) for _ in [0]*(n-1)]
    m = int(input())
    uv = [list(map(int, input().split())) for _ in [0]*m]
    g = [[] for _ in [0]*n]
    [g[a-1].append(b-1) for a, b in ab]
    [g[b-1].append(a-1) for a, b in ab]

    d = dict()
    for i, (a, b) in enumerate(ab):
        d[(a-1, b-1)] = i

    def tree_path(root, goal):
        d = [-1]*n  
        d[root] = 0
        q = [root]
        cnt = 0
        while q:  
            cnt += 1
            qq = []
            while q:
                i = q.pop()
                for j in g[i]:
                    if d[j] == -1:
                        d[j] = cnt
                        qq.append(j)
            q = qq
        now = goal
        path = [goal]
        while True:
            dist = d[now]
            for i in g[now]:
                if d[i] < dist:
                    now = i
                    path.append(i)
                    break
            if dist == 1:
                break
        return path

    seiyaku = [set() for _ in [0]*m]

    for i, (u, v) in enumerate(uv):
        path = tree_path(u-1, v-1)
        for j in range(len(path)-1):
            x, y = min(path[j], path[j+1]), max(path[j], path[j+1])
            seiyaku[i].add(d[(x, y)])

    cnt = 2**(n-1)

    for i in range(1, m+1):
        flag = 1
        if i % 2 == 1:
            flag = -1
        cc = combinations(list(range(m)), i)
        for c in cc:
            s = set()
            for j in c:
                s |= seiyaku[j]
            cnt += (2**(n-1-len(s)))*flag
    print(cnt)


main()