Problem:


Score : 600 points

Problem Statement

Given is a tree T with N vertices. The i-th edge connects Vertex A_i and B_i (1 \leq A_i,B_i \leq N).

Now, each vertex is painted black with probability 1/2 and white with probability 1/2, which is chosen independently from other vertices. Then, let S be the smallest subtree (connected subgraph) of T containing all the vertices painted black. (If no vertex is painted black, S is the empty graph.)

Let the holeyness of S be the number of white vertices contained in S. Find the expected holeyness of S.

Since the answer is a rational number, we ask you to print it \bmod 10^9+7, as described in Notes.

Notes

When you print a rational number, first write it as a fraction \frac{y}{x}, where x, y are integers, and x is not divisible by 10^9 + 7
(under the constraints of the problem, such representation is always possible).

Then, you need to print the only integer z between 0 and 10^9 + 6, inclusive, that satisfies xz \equiv y \pmod{10^9 + 7}.

Constraints

2 \leq N \leq 2 \times 10^5

1 \leq A_i,B_i \leq N

The given graph is a tree.

Input

Input is given from Standard Input in the following format:

N
A_1 B_1
:
A_{N-1} B_{N-1}

Output

Print the expected holeyness of S, \bmod 10^9+7.

Sample Input 1

3
1 2
2 3

Sample Output 1

125000001

If the vertices 1, 2, 3 are painted black, white, black, respectively, the holeyness of S is 1.

Otherwise, the holeyness is 0, so the expected holeyness is 1/8.

Since 8 \times 125000001 \equiv 1 \pmod{10^9+7}, we should print 125000001.

Sample Input 2

4
1 2
2 3
3 4

Sample Output 2

375000003

The expected holeyness is 3/8.

Since 8 \times 375000003 \equiv 3 \pmod{10^9+7}, we should print 375000003.

Sample Input 3

4
1 2
1 3
1 4

Sample Output 3

250000002

The expected holeyness is 1/4.

Sample Input 4

7
4 7
3 1
2 6
5 2
7 1
2 7

Sample Output 4

570312505



Sample input:
3
1 2
2 3


Sample output:
125000001

Submission status: Wrong Answer

Solution code:
import sys
mod = pow(10, 9) + 7
sys.setrecursionlimit(pow(10, 8))

def power(x, y):
    if   y == 0     : return 1
    elif y == 1     : return x % mod
    elif y % 2 == 0 : return power(x, y//2)**2 % mod
    else            : return power(x, (y-1)//2)**2 * x % mod
    
def mul(a, b):
    return ((a % mod) * (b % mod)) % mod

def div(a, b):
    return mul(a, power(b, mod-2))

def cmb(n, r, mod):
    if ( r<0 or r>n ):
        return 0
    r = min(r, n-r)
    return g1[n] * g2[r] * g2[n-r] % mod

import sys
from collections import defaultdict
input = sys.stdin.readline

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

v2i = [0 for _ in range(N+1)]
def itt(v, p):
    cn = 0
    ms = []
    for u in G[v]:
        if u == p:
            continue
        un = itt(u, v)
        ms.append(un)
        cn += un
    if p != None:
        ms.append(N-1-cn)
    v2i[v] = ms
    return cn+1
itt(1, None)
r = 0
for v in range(1, N+1):
    ff = v2i[v]
    for f in ff:
        r += 2- 1
xx = power(2,N-1)
print((div(N*xx-N-r, xx*2%mod))%mod)

Submission status: Time Limit Exceeded

Solution code:
# 75

import sys
sys.setrecursionlimit(10**8)

MOD = 10**9+7
N = int(input())
g_l = [[] for i in range(N)]
check_l = [-1] * N
num_l = [0] * N
for i in range(N-1):
    ai, bi = map(int, input().split())
    g_l[ai-1].append(bi-1)
    g_l[bi-1].append(ai-1)


def dfs(n):
    d = 1
    if check_l[n] > 0:
        return num_l[n]
    check_l[n] = 1
    for next_n in g_l[n]:
        d += dfs(next_n)
    num_l[n] = d
    return d


def modpow(a, n):
    # calc : (a**n)%MOD
    ret = 1
    while n > 0:
        if n & 1:
            ret = (ret * a) % MOD
        a = (a * a) % MOD
        n >>= 1
    return ret


def modinv(a):
    # calc : (a**(-1)) %MOD
    return modpow(a, MOD-2)


dfs(0)

ans = 0
# for i in range(1, N):
#     ans += (1 - (1/2)**num_l[i]) * (1 - (1/2)**(N-num_l[i]))
# ans += 1 - (1/2)**N  # 辺の期待値→頂点の期待値に変換(空集合以外は+1される)
# ans -= N/2  # 黒点の期待値を引く
for i in range(1, N):
    ans = (ans + (pow(2, num_l[i], MOD)-1) *
           (pow(2, N-num_l[i])-1) % MOD) % MOD
ans = (ans + (pow(2, N, MOD) - 1) - (N * pow(2, N-1, MOD)) % MOD) % MOD
y = ans
x = pow(2, N, MOD)

z = (y * modinv(x)) % MOD

print(z)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(500000)
input = sys.stdin.readline
N = int(input()); MOD=pow(10,9)+7

beki = [-1]*(N+1); beki[0] = 1; beki[1] = 2 #階乗
for i in range(2,N+1):
  beki[i] = beki[i-1]*2%MOD
#print(beki)

G = [[] for _ in range(N)]
for i in range(N-1):
  a,b = map(int,input().split())
  a-=1;b-=1
  G[a].append(b);G[b].append(a)
#print(G)
ans = 0

def dfs(v,p): #自分と親
  global ans #ansをGlobal変数として宣言
  res = 1 #戻り値。vを含めた部分木のサイズ。自分の分で最初は1
  ts = [] #vから生えている部分木のリスト
  for u in G[v]:
    if u == p:
      continue
    t = dfs(u,v) #uの部分木のサイズが戻り値
    res += t
    ts.append(t)
  if p != -1: #根以外なら親側の部分木が存在する。
    ts.append(N-res)
  now = beki[N-1] - 1 #自分以外を決めるのが2^(N-1)通り。自分以外が全部0が1通り。
  for x in ts:
    now -= beki[x] - 1 #各部分木に一個以上黒がある場合の数。全通り - 全部白
  ans = (ans+now)%MOD
  return res #vを含めた部分木のサイズ

dfs(0,-1)
ALL = beki[N]
#print(ans,ALL)
ans = ans*pow(ALL,MOD-2,MOD)%MOD #フェルマーの小定理より1/ALL = ALL^(MOD-2)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(500000)
input = sys.stdin.readline
N = int(input()); MOD=pow(10,9)+7
G = [[] for _ in range(N)]
for i in range(N-1):
  a,b = map(int,input().split())
  a-=1;b-=1
  G[a].append(b);G[b].append(a)
#print(G)
ans = 0

def dfs(v,p): #自分と親
  global ans #ansをGlobal変数として宣言
  res = 1 #戻り値。vを含めた部分木のサイズ。自分の分で最初は1
  ts = [] #vから生えている部分木のリスト
  for u in G[v]:
    if u == p:
      continue
    t = dfs(u,v) #uの部分木のサイズが戻り値
    res += t
    ts.append(t)
  if p != -1: #根以外なら親側の部分木が存在する。
    ts.append(N-res)
  now = pow(2,N-1,MOD) - 1 #自分以外を決めるのが2^(N-1)通り。自分以外が全部0が1通り。
  for x in ts:
    now -= pow(2,x,MOD) - 1 #各部分木に一個以上黒がある場合の数。全通り - 全部白
  ans = (ans+now)%MOD
  return res #vを含めた部分木のサイズ

dfs(0,-1)
ALL = pow(2,N,MOD)
#print(ans,ALL)
ans = ans*pow(ALL,MOD-2,MOD)%MOD #フェルマーの小定理より1/ALL = ALL^(MOD-2)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(500000)
N = int(input()); MOD=pow(10,9)+7
G = [[] for _ in range(N)]
for i in range(N-1):
  a,b = map(int,input().split())
  a-=1;b-=1
  G[a].append(b);G[b].append(a)
#print(G)
ans = 0

def dfs(v,p): #自分と親
  global ans #ansをGlobal変数として宣言
  res = 1 #戻り値。vを含めた部分木のサイズ。自分の分で最初は1
  ts = [] #vから生えている部分木のリスト
  for u in G[v]:
    if u == p:
      continue
    t = dfs(u,v) #uの部分木のサイズが戻り値
    res += t
    ts.append(t)
  if p != -1: #根以外なら親側の部分木が存在する。
    ts.append(N-res)
  now = pow(2,N-1,MOD) - 1 #自分以外を決めるのが2^(N-1)通り。自分以外が全部0が1通り。
  for x in ts:
    now -= pow(2,x,MOD) - 1 #各部分木に一個以上黒がある場合の数。全通り - 全部白
  ans = (ans+now)%MOD
  return res #vを含めた部分木のサイズ

dfs(0,-1)
ALL = pow(2,N,MOD)
#print(ans,ALL)
ans = ans*pow(ALL,MOD-2,MOD)%MOD #フェルマーの小定理より1/ALL = ALL^(MOD-2)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
# classを使うのをやめてlistで実施する
# dfsを再帰でなくstackを用いて書く
from collections import deque
import sys
input = sys.stdin.readline

def dfs():
    stk1 = deque([0])
    stk2 = deque([])
    while stk1:
        v = stk1.pop()
        visited[v] = True
        stk2.append(v)
        for i in range(len(AL[v][CHILDREN])):
            u = AL[v][CHILDREN][i]
            if visited[u]:
                AL[v][CHILDREN][i] = None
                continue
            stk1.append(u)

    for i in range(n - 1, -1, -1):
        v = stk2[i]
        for u in AL[v][CHILDREN]:
            if u is None:  continue
            AL[v][SIZE] += AL[u][SIZE]

def anaaki(v):
    ret = pow(2, n - 1, p) - 1
    for ch in AL[v][CHILDREN]:
        if ch is None: continue
        ret -= pow(2, AL[ch][SIZE], p) - 1
        ret %= p
    ret -= pow(2, n - AL[v][SIZE], p) - 1
    ret %= p
    return ret

n = int(input())
SIZE = 0
CHILDREN = 1
AL = [[1, []] for _ in range(n)]
visited = [False] * n
p = 10 ** 9 + 7

for i in range(n - 1):
    a, b = [int(x) - 1 for x in input().split()]
    AL[a][CHILDREN].append(b)
    AL[b][CHILDREN].append(a)

dfs()
numer = 0
for i in range(n):
    numer += anaaki(i)
    numer %= p

denom = pow(2, n, p)
print(numer * pow(denom, p - 2, p) % p)

Submission status: Time Limit Exceeded

Solution code:
# classを使うのをやめてlistで実施する
from collections import deque
import sys
sys.setrecursionlimit(10 ** 9)
import sys
input = sys.stdin.readline

def dfs(v):
    visited[v] = True
    for i in range(len(AL[v][CHILDREN])):
        u = AL[v][CHILDREN][i]
        if visited[u]:
            AL[v][CHILDREN][i] = None
            continue
        AL[v][SIZE] += dfs(u)
    return AL[v][SIZE]

def anaaki(v):
    ret = pow(2, n - 1, p) - 1
    for ch in AL[v][CHILDREN]:
        if ch is None: continue
        ret -= pow(2, AL[ch][SIZE], p) - 1
        ret %= p
    ret -= pow(2, n - AL[v][SIZE], p) - 1
    ret %= p
    return ret

n = int(input())
SIZE = 0
CHILDREN = 1
AL = [[1, []] for _ in range(n)]
visited = [False] * n
p = 10 ** 9 + 7
for i in range(n - 1):
    a, b = [int(x) - 1 for x in input().split()]
    AL[a][CHILDREN].append(b)
    AL[b][CHILDREN].append(a)

dfs(0)
numer = 0
for i in range(n):
    numer += anaaki(i)
    numer %= p

denom = pow(2, n, p)
print(numer * pow(denom, p - 2, p) % p)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import sys
sys.setrecursionlimit(10 ** 9)
import sys
input = sys.stdin.readline

def dfs(v):
    visited[v] = True
    for i in range(len(AL[v][CHILDREN])):
        u = AL[v][CHILDREN][i]
        if visited[u]:
            AL[v][CHILDREN][i] = None
            continue
        AL[v][SIZE] += dfs(u)
    return AL[v][SIZE]

def anaaki(v):
    ret = pow(2, n - 1, p) - 1
    for ch in AL[v][CHILDREN]:
        if ch is None: continue
        ret -= pow(2, AL[ch][SIZE], p) - 1
        ret %= p
    ret -= pow(2, n - AL[v][SIZE], p) - 1
    ret %= p
    return ret

n = int(input())
SIZE = 0
CHILDREN = 1
AL = [[1, []] for _ in range(n)]
visited = [False] * n
p = 10 ** 9 + 7
for i in range(n - 1):
    a, b = [int(x) - 1 for x in input().split()]
    AL[a][CHILDREN].append(b)
    AL[b][CHILDREN].append(a)

dfs(0)
que = deque([0])
numer = 0
while que:
    next = que.popleft()
    numer += anaaki(next)
    numer %= p
    for ch in AL[next][CHILDREN]:
        if ch is not None:
            que.append(ch)

denom = pow(2, n, p)
print(numer * pow(denom, p - 2, p) % p)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import sys
sys.setrecursionlimit(10 ** 9)
input = sys.stdin.readline

class Node:
    def __init__(self):
        self.size = 1  # 自分以下のノードの数
        self.children = []

def dfs(v):
    V = Node()
    visited[v] = True
    for u in AL[v]:
        if visited[u]: continue
        U = dfs(u)
        V.size += U.size
        V.children.append(U)
    return V

def anaaki(V):
    ret = pow(2, n - 1, p) - 1
    for ch in V.children:
        ret -= pow(2, ch.size, p) - 1
        ret %= p
    ret -= pow(2, n - V.size, p) - 1
    ret %= p
    return ret

n = int(input())
AL = [[] for _ in range(n)]
visited = [False] * n
p = 10 ** 9 + 7
for i in range(n - 1):
    a, b = [int(x) - 1 for x in input().split()]
    AL[a].append(b)
    AL[b].append(a)

# dfs
root = dfs(0)
que = deque([root])
numer = 0
while que:
    next = que.popleft()
    numer += anaaki(next)
    numer %= p
    for ch in next.children:
        que.append(ch)

denom = pow(2, n, p)

print( numer * pow(denom, p - 2, p) % p)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import sys
sys.setrecursionlimit(10 ** 9)
input = sys.stdin.readline

class Node:
    def __init__(self):
        self.size = 1  # 自分以下のノードの数
        self.children = []

def dfs(v):
    V = Node()
    visited[v] = True
    for u in AL[v]:
        if visited[u]: continue
        U = dfs(u)
        V.size += U.size
        V.children.append(U)
    return V

def anaaki(V):
    ret = pow(2, n - 1, p) - 1
    for ch in V.children:
        ret -= pow(2, ch.size) - 1
        ret %= p
    ret -= pow(2, n - V.size) - 1
    ret %= p
    return ret

n = int(input())
AL = [[] for _ in range(n)]
visited = [False] * n
p = 10 ** 9 + 7
for i in range(n - 1):
    a, b = [int(x) - 1 for x in input().split()]
    AL[a].append(b)
    AL[b].append(a)

# dfs
root = dfs(0)
que = deque([root])
numer = 0
while que:
    next = que.popleft()
    numer += anaaki(next)
    numer %= p
    for ch in next.children:
        que.append(ch)

denom = pow(2, n, p)

print( numer * pow(denom, p - 2, p) % p)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import sys
sys.setrecursionlimit(10 ** 9)

class Node:
    def __init__(self):
        self.size = 1  # 自分以下のノードの数
        self.children = []

def dfs(v):
    V = Node()
    visited[v] = True
    for u in AL[v]:
        if visited[u]: continue
        U = dfs(u)
        V.size += U.size
        V.children.append(U)
    return V

def anaaki(V):
    ret = pow(2, n - 1, p) - 1
    for ch in V.children:
        ret -= pow(2, ch.size) - 1
        ret %= p
    ret -= pow(2, n - V.size) - 1
    ret %= p
    return ret

n = int(input())
AL = [[] for _ in range(n)]
visited = [False] * n
p = 10 ** 9 + 7
for i in range(n - 1):
    a, b = [int(x) - 1 for x in input().split()]
    AL[a].append(b)
    AL[b].append(a)

# dfs
root = dfs(0)
que = deque([root])
numer = 0
while que:
    next = que.popleft()
    numer += anaaki(next)
    numer %= p
    for ch in next.children:
        que.append(ch)

denom = pow(2, n, p)

print( numer * pow(denom, p - 2, p) % p)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import sys
sys.setrecursionlimit(10 ** 9)

class Node:
    def __init__(self):
        self.size = 1  # 自分以下のノードの数
        self.children = []

def dfs(v):
    V = Node()
    visited[v] = True
    for u in AL[v]:
        if visited[u]: continue
        U = dfs(u)
        V.size += U.size
        V.children.append(U)
    return V

def anaaki(V):
    ret = pow(2, n - 1, p) - 1
    for ch in V.children:
        ret -= pow(2, ch.size) - 1
        ret %= p
    ret -= pow(2, n - V.size) - 1
    ret %= p
    return ret

n = int(input())
AL = [[] for _ in range(n)]
visited = [False] * n
p = 10 ** 9 + 7
for i in range(n - 1):
    a, b = [int(x) - 1 for x in input().split()]
    AL[a].append(b)
    AL[b].append(a)

# dfs
root = dfs(0)
que = deque([root])
numer = 0
while que:
    next = que.popleft()
    numer += anaaki(next)
    numer %= p
    for ch in next.children:
        que.append(ch)

denom = pow(2, n, p)

print( numer * pow(denom, p - 2, p) % p)

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
from operator import mul
from functools import reduce
from operator import mul


sys.setrecursionlimit(2147483647)
INF = 10 ** 20
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
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)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 1000000007


n = I()
G = [[] for _ in range(n)]
for _ in range(n - 1):
    a, b = LI()
    G[a - 1] += [b - 1]
    G[b - 1] += [a - 1]


par = [-1] * n
cnt = [0] * n


def f(u):
    ret = 1
    for v in G[u]:
        if v == par[u]:
            continue
        par[v] = u
        ret += f(v)
    cnt[u] = ret
    return ret

f(0)
pow2 = [1] * (n + 1)
for i in range(1, n + 1):
    pow2[i] = pow2[i - 1] * 2 % mod

q = deque([0])
ans = 0
while q:
    u = q.pop()
    ret = pow2[n - 1] - 1
    for v in G[u]:
        if v == par[u]:
            continue
        ret -= pow2[cnt[v]] - 1
        q += [v]
    ret -= pow2[n - cnt[u]] - 1
    ans = (ans + ret) % mod

print(ans * pow(pow2[n], mod - 2, mod) % mod)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**6)
mod = 10**9+7
p2 = [1]*(3*10**5)
for n in range(3*10**5-1):
    p2[n+1] = p2[n]*2%mod

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

l1 = [0]*(N+1)
l2 = [[] for _ in range(N+1)]

def rec(p,c):
    res = 0
    for a in g[c]:
        if a == p:
            continue
        n = rec(c,a)
        l2[c].append(n+1)
        res += n+1
    l1[c] = res
    return res

n = rec(0,1)
for i in range(1,N+1):
    l2[i].append(N-1-l1[i])

ans = 0
for i in range(1,N+1):
    ans += p2[N-1]-1
    ans %= mod
    for j in l2[i]:
        ans -= p2[j]-1
        ans %= mod
ans *= pow(p2[N],mod-2,mod)
ans %= mod
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict
import sys


sys.setrecursionlimit(10 ** 6)


def ext_euc(a, b):
    if b == 0:
        return 1, 0, a
    y, x, v = ext_euc(b, a % b)
    y -= (a // b) * x
    return x, y, v


def mod_inv(a, mod):
    x, _, _ = ext_euc(a, mod)
    return x % mod


def main():
    MOD = 10 ** 9 + 7
    N = int(input())
    adj = defaultdict(list)
    for _ in range(N - 1):
        A, B = list(map(lambda x: int(x) - 1, input().split()))
        adj[A].append(B)
        adj[B].append(A)

    # 2 ** n の事前計算
    pow_2 = [1 for _ in range(N + 1)]
    for i in range(1, N + 1):
        pow_2[i] = pow_2[i - 1] * 2 % MOD

    # 分子：sum_{i} (node i が穴あき度の値としてカウント対象になるような塗り方)
    # node_num[(node, dir_node)]: nodeから見てdir_node方向に存在するノードの数
    #         5               6
    #        (6)             (6)
    #         |               |
    #        (1)             (1)
    # 0(6)-(1)1(4)-(3)2(3)-(4)3(1)-(6)4
    node_num = defaultdict(int)

    def dfs(node=0, parent=None):
        child_list = [n for n in adj[node] if n != parent]
        if len(child_list) == 0:
            node_num[(node, parent)] = N - 1
            node_num[(parent, node)] = 1
            return 1
        n_descendant = 1  # self
        for child in child_list:
            n_descendant += dfs(child, node)
        if parent is not None:
            node_num[(node, parent)] = N - n_descendant
            node_num[(parent, node)] = n_descendant
        return n_descendant

    dfs()

    numer = 0
    for node in range(N):
        if len(adj[node]) <= 1:
            # 端（次数1）のノードはカウント対象にならない
            continue
        cnt_not = 0  # node が穴あき度の値としてカウントされないケース
        for dir_node in adj[node]:
            # dir_node方向のノードは自由、それ以外の方向のノードは全部白
            cnt_not += pow_2[node_num[(node, dir_node)]]
        cnt_not -= len(adj[node]) - 1  # 「全部白塗り」の重複カウントを除去
        numer += pow_2[N - 1] - cnt_not  # node自身は白でないとカウントされないので、全体のパターン数が2 ** (N-1)

    # 分母：2 ** N （全部の塗り方）
    denom = pow_2[N]

    # 答え
    print(numer * mod_inv(denom, MOD) % MOD)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)

mod = 10**9 + 7
N = int(input())
G = [[] for _ in range(N)]
for _ in range(N-1):
    A, B = map(int, input().split())
    A -= 1
    B -= 1
    G[A].append(B)
    G[B].append(A)

parent = [-1] * N
size = [1] * N

def dfs(v, p):
    parent[v] = p
    for c in G[v]:
        if c == p:
            continue
        dfs(c, v)
        size[v] += size[c]

dfs(0, -1)
ans = 0
two_inv = pow(2, mod - 2, mod)
prob0 = pow(two_inv, N, mod)
for v in range(N):
    prob1 = 0
    s = 1
    for c in G[v]:
        if c == parent[v]:
            continue
        s += size[c]
        prob1 = (prob1 + pow(two_inv, N - size[c]) - prob0) % mod
    prob1 = (prob1 + pow(two_inv, s, mod) - prob0) % mod
    prob = (two_inv - prob0 - prob1) % mod
    ans = (ans + prob) % mod
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)

mod = 10**9 + 7
N = int(input())
G = [[] for _ in range(N)]
for _ in range(N-1):
    A, B = map(int, input().split())
    A -= 1
    B -= 1
    G[A].append(B)
    G[B].append(A)

parent = [-1] * N
size = [1] * N

def dfs(v, p):
    parent[v] = p
    for c in G[v]:
        if c == p:
            continue
        dfs(c, v)
        size[v] += size[c]

dfs(0, -1)
ans = 0
two_inv = pow(2, mod - 2, mod)
for v in range(N):
    prob1 = 0
    s = 1
    for c in G[v]:
        if c == parent[v]:
            continue
        s += size[c]
        prob1 += (1 - pow(two_inv, size[c], mod)) * pow(two_inv, N - size[c], mod) % mod
        prob1 %= mod
    prob1 += (1 - pow(two_inv, N - s, mod)) * pow(two_inv, s, mod) % mod
    prob1 %= mod
    prob = (two_inv - pow(two_inv, N, mod) - prob1) % mod
    ans = (ans + prob) % mod
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)

mod = 10**9 + 7
N = int(input())
G = [[] for _ in range(N)]
for _ in range(N-1):
    A, B = map(int, input().split())
    A -= 1
    B -= 1
    G[A].append(B)
    G[B].append(A)

parent = [-1] * N
size = [1] * N

def dfs(v, p):
    parent[v] = p
    for c in G[v]:
        if c == p:
            continue
        dfs(c, v)
        size[v] += size[c]

dfs(0, -1)
ans = 0
for v in range(N):
    prob1 = 0
    s = 1
    for c in G[v]:
        if c == parent[v]:
            continue
        s += size[c]
        prob1 += (1 - pow(2, size[c] * (mod - 2), mod)) * pow(2, (N - size[c]) * (mod - 2), mod) % mod
        prob1 %= mod
    prob1 += (1 - pow(2, (N - s) * (mod - 2), mod)) * pow(2, s * (mod - 2), mod) % mod
    prob1 %= mod
    prob = pow(2, mod - 2, mod) - pow(2, N * (mod - 2), mod) - prob1
    prob %= mod
    ans = (ans + prob) % mod
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)

mod = 10**9 + 7
N = int(input())
G = [[] for _ in range(N)]
for _ in range(N-1):
    A, B = map(int, input().split())
    A -= 1
    B -= 1
    G[A].append(B)
    G[B].append(A)

ans = 0
size = [1] * N

def dfs(v, p):
    for c in G[v]:
        if c == p:
            continue
        dfs(c, v)
        size[v] += size[c]

dfs(0, -1)

def dfs2(v, p):
    global ans
    prob1 = 0
    s = 1
    for c in G[v]:
        if c == p:
            continue
        s += size[c]
        prob1 += (1 - pow(2, size[c] * (mod - 2), mod)) * pow(2, (N - size[c]) * (mod - 2), mod) % mod
        prob1 %= mod
        dfs2(c, v)
    prob1 += (1 - pow(2, (N - s) * (mod - 2), mod)) * pow(2, s * (mod - 2), mod) % mod
    prob1 %= mod
    prob = pow(2, mod - 2, mod) - pow(2, N * (mod - 2), mod) - prob1
    prob %= mod
    ans = (ans + prob) % mod

dfs2(0, -1)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
# https://atcoder.jp/contests/abc149/tasks/abc149_f
import sys
sys.setrecursionlimit(10**8)
mod = 10**9 + 7

N = int(input())
G = [[] for i in range(N+1)]
for i in range(N-1):
    a, b = map(int, input().split())
    G[a].append(b)
    G[b].append(a)

visited = set()
parent = [-1 for i in range(N+1)]
count = [1 for i in range(N+1)]
ans = N*pow(2, N-1, mod)


def dfs(node):
    visited.add(node)
    for child in G[node]:
        if child not in visited:
            parent[child] = node
            dfs(child)
    for child in G[node]:
        if child != parent[node]:
            count[node] += count[child]


start = -1
for i in range(1, N+1):
    if len(G[i]) == 1:
        start = i
        break
dfs(start)

ans = 0
for i in range(1, N+1):
    if len(G[i]) > 1:
        ans += pow(2, N-1, mod)
        for x in G[i]:
            if x != parent[i]:
                ans -= pow(2, count[x], mod)
        ans -= pow(2, N-count[i], mod)
        ans += len(G[i]) - 1
        ans %= mod
D = pow(2, N, mod)
print(ans*pow(D, mod-2, mod) % mod)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**6)

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


def dfs(v, p=-1):
  global ans

  res = 1
  ts = []
  for u in adj[v]:
    if (u==p): continue
    t = dfs(u,v)
    res += t
    ts.append(t)

  if p != -1:
    ts.append(N-res)

  # print(v, ts)

  now = pow(2, N-1, MOD)-1
  for t in ts:
    now -= pow(2, t, MOD)-1
  ans += now
  return res

ans = 0
MOD = 10**9+7
dfs(1)
print((ans * pow(pow(2, N, MOD), MOD-2, MOD)) % MOD)

Submission status: Time Limit Exceeded

Solution code:
# Surrounded Nodes
from collections import deque
import sys
sys.setrecursionlimit(10**8)
mod = 10**9 + 7
N = int(input())
G = [[] for i in range(N+1)]
for i in range(N-1):
    a, b = map(int, input().split())
    G[a].append(b)
    G[b].append(a)
S = -1
for i in range(1, N+1):
    if len(G[i]) == 1:
        S = i
        break
visited = [False for i in range(N+1)]
parent = [-1 for i in range(N+1)]
count = [1 for i in range(N+1)]

ans = N*pow(2, N-1, mod)
stack = deque()


def dfs(node):
    visited[node] = True
    for child in G[node]:
        if visited[child] == False:
            parent[child] = node
            stack.append((node, child))
            dfs(child)


powers = [1 for i in range(2*10**5+1)]
for i in range(1, 2*10**5+1):
    powers[i] = powers[i-1]*2 % mod

dfs(S)
while stack:
    mom, child = stack.pop()
    count[mom] += count[child]
ans = 0
for i in range(1, N+1):
    if len(G[i]) > 1:
        ans += powers[N-1]
        for x in G[i]:
            if x != parent[i]:
                ans -= powers[count[x]]
        ans -= powers[N-count[i]]
        ans += len(G[i]) - 1
        ans %= mod
D = pow(2, N, mod)
print(ans*pow(D, mod-2, mod) % mod)

Submission status: Time Limit Exceeded

Solution code:
# Surrounded Nodes
from collections import deque
import sys
sys.setrecursionlimit(10**8)
mod = 10**9 + 7
N = int(input())
G = [[] for i in range(N+1)]
for i in range(N-1):
    a, b = map(int, input().split())
    G[a].append(b)
    G[b].append(a)
S = -1
for i in range(1, N+1):
    if len(G[i]) == 1:
        S = i
        break
visited = [False for i in range(N+1)]
parent = [-1 for i in range(N+1)]
count = [1 for i in range(N+1)]

ans = N*pow(2, N-1, mod)
stack = deque()


def dfs(node):
    visited[node] = True
    for child in G[node]:
        if visited[child] == False:
            parent[child] = node
            stack.append((node, child))
            dfs(child)


dfs(S)
while stack:
    mom, child = stack.pop()
    count[mom] += count[child]
ans = 0
for i in range(1, N+1):
    if len(G[i]) > 1:
        ans += pow(2, N-1, mod)
        for x in G[i]:
            if x != parent[i]:
                ans -= pow(2, count[x], mod)
        ans -= pow(2, N-count[i], mod)
        ans += len(G[i]) - 1
D = pow(2, N, mod)
print(ans*pow(D, mod-2, mod) % mod)

Submission status: Time Limit Exceeded

Solution code:
import sys
import itertools
# import numpy as np
import time
import math
import heapq
from collections import defaultdict
sys.setrecursionlimit(10 ** 7)
 
INF = 10 ** 9 + 7
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

# map(int, input().split())

MOD = 10 ** 9 + 7
def my_pow(base, n, mod):
    if n == 0:
        return 1
    x = base
    y = 1
    while n > 1:
        if n % 2 == 0:
            x *= x
            n //= 2
        else:
            y *= x
            n -= 1
        x %= mod
        y %= mod
    return x * y % mod

N = int(input())

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

pows = [1] * N
for i in range(1, N):
    pows[i] = (pows[i - 1] * 2) % MOD

ans = 0
def dfs(v, p):
    global ans
    subs = []
    res = 1
    for u in adj[v]:
        if u == p:
            continue
        val = dfs(u, v)
        res += val
        subs.append(val)
    # add sub-tree on the parent side
    if p != -1:
        subs.append(N - res)
    now = pows[N - 1] - 1 # N - 1 means that it chooses freelye other than v
    for sub in subs:
        now -= pows[sub] - 1
    ans += now
    ans %= MOD
    return res

dfs(0, -1)
print(ans * my_pow(2 ** N, MOD - 2, MOD) % MOD)

Submission status: Time Limit Exceeded

Solution code:
import sys
import itertools
# import numpy as np
import time
import math
import heapq
from collections import defaultdict
sys.setrecursionlimit(10 ** 7)
 
INF = 10 ** 9 + 7
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

# map(int, input().split())

MOD = 10 ** 9 + 7
def my_pow(base, n, mod):
    if n == 0:
        return 1
    x = base
    y = 1
    while n > 1:
        if n % 2 == 0:
            x *= x
            n //= 2
        else:
            y *= x
            n -= 1
        x %= mod
        y %= mod
    return x * y % mod

N = int(input())

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

pows = [0] * N
for i in range(N):
    pows[i] = (my_pow(2, i, MOD))

ans = 0
def dfs(v, p):
    global ans
    subs = []
    res = 1
    for u in adj[v]:
        if u == p:
            continue
        val = dfs(u, v)
        res += val
        subs.append(val)
    # add sub-tree on the parent side
    if p != -1:
        subs.append(N - res)
    now = pows[N - 1] - 1 # N - 1 means that it chooses freelye other than v
    for sub in subs:
        now -= pows[sub] - 1
    ans += now
    ans %= MOD
    return res

dfs(0, -1)
print(ans * my_pow(2 ** N, MOD - 2, MOD) % MOD)

Submission status: Time Limit Exceeded

Solution code:
import sys
import itertools
# import numpy as np
import time
import math
import heapq
from collections import defaultdict
sys.setrecursionlimit(10 ** 7)
 
INF = 10 ** 9 + 7
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

# map(int, input().split())

MOD = 10 ** 9 + 7
def my_pow(base, n, mod):
    if n == 0:
        return 1
    x = base
    y = 1
    while n > 1:
        if n % 2 == 0:
            x *= x
            n //= 2
        else:
            y *= x
            n -= 1
        x %= mod
        y %= mod
    return x * y % mod

N = int(input())

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

pows = []
for i in range(N):
    pows.append(my_pow(2, i, MOD))

ans = 0
def dfs(v, p):
    global ans
    subs = []
    res = 1
    for u in adj[v]:
        if u == p:
            continue
        val = dfs(u, v)
        res += val
        subs.append(val)
    # add sub-tree on the parent side
    if p != -1:
        subs.append(N - res)
    now = pows[N - 1] - 1 # N - 1 means that it chooses freelye other than v
    for sub in subs:
        now -= pows[sub] - 1
    ans += now
    ans %= MOD
    return res

dfs(0, -1)
print(ans * my_pow(2 ** N, MOD - 2, MOD) % MOD)