Problem:


Score : 100 points

Problem Statement

There is a tree with N vertices, numbered 1, 2, \ldots, N.
For each i (1 \leq i \leq N - 1), the i-th edge connects Vertex x_i and y_i.

Taro has decided to paint each vertex in white or black.
Here, it is not allowed to paint two adjacent vertices both in black.

Find the number of ways in which the vertices can be painted, modulo 10^9 + 7.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq x_i, y_i \leq N

The given graph is a tree.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
x_2 y_2
:
x_{N - 1} y_{N - 1}

Output

Print the number of ways in which the vertices can be painted, modulo 10^9 + 7.

Sample Input 1

3
1 2
2 3

Sample Output 1

5

There are five ways to paint the vertices, as follows:

Sample Input 2

4
1 2
1 3
1 4

Sample Output 2

9

There are nine ways to paint the vertices, as follows:

Sample Input 3

1

Sample Output 3

2

Sample Input 4

10
8 5
10 8
6 5
1 5
4 8
2 10
3 6
9 2
1 7

Sample Output 4

157



Sample input:
3
1 2
2 3


Sample output:
5

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-

#############
# Libraries #
#############

import sys
input = sys.stdin.readline

import math
#from math import gcd
import bisect
import heapq
from collections import defaultdict
from collections import deque
from collections import Counter
from functools import lru_cache

#############
# Constants #
#############

MOD = 10**9+7
INF = float('inf')
AZ = "abcdefghijklmnopqrstuvwxyz"

#############
# Functions #
#############

######INPUT######
def I(): return int(input().strip())
def S(): return input().strip()
def IL(): return list(map(int,input().split()))
def SL(): return list(map(str,input().split()))
def ILs(n): return list(int(input()) for _ in range(n))
def SLs(n): return list(input().strip() for _ in range(n))
def ILL(n): return [list(map(int, input().split())) for _ in range(n)]
def SLL(n): return [list(map(str, input().split())) for _ in range(n)]

######OUTPUT######
def P(arg): print(arg); return
def Y(): print("Yes"); return
def N(): print("No"); return
def E(): exit()
def PE(arg): print(arg); exit()
def YE(): print("Yes"); exit()
def NE(): print("No"); exit()

#####Shorten#####
def DD(arg): return defaultdict(arg)

#####Inverse#####
def inv(n): return pow(n, MOD-2, MOD)

######Combination######
kaijo_memo = []
def kaijo(n):
  if(len(kaijo_memo) > n): return kaijo_memo[n]
  if(len(kaijo_memo) == 0): kaijo_memo.append(1)
  while(len(kaijo_memo) <= n): kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
  return kaijo_memo[n]

gyaku_kaijo_memo = []
def gyaku_kaijo(n):
  if(len(gyaku_kaijo_memo) > n): return gyaku_kaijo_memo[n]
  if(len(gyaku_kaijo_memo) == 0): gyaku_kaijo_memo.append(1)
  while(len(gyaku_kaijo_memo) <= n): gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD)
  return gyaku_kaijo_memo[n]

def nCr(n,r):
  if n == r: return 1
  if n < r or r < 0: return 0
  ret = 1
  ret = ret * kaijo(n) % MOD
  ret = ret * gyaku_kaijo(r) % MOD
  ret = ret * gyaku_kaijo(n-r) % MOD
  return ret

######Factorization######
def factorization(n):
  arr = []
  temp = n
  for i in range(2, int(-(-n**0.5//1))+1):
    if temp%i==0:
      cnt=0
      while temp%i==0: 
        cnt+=1 
        temp //= i
      arr.append([i, cnt])
  if temp!=1: arr.append([temp, 1])
  if arr==[]: arr.append([n, 1])
  return arr

#####MakeDivisors######
def make_divisors(n):
  divisors = []
  for i in range(1, int(n**0.5)+1):
    if n % i == 0:
      divisors.append(i)
      if i != n // i: 
        divisors.append(n//i)
  return divisors

#####MakePrimes######
def make_primes(N):
  max = int(math.sqrt(N))
  seachList = [i for i in range(2,N+1)]
  primeNum = []
  while seachList[0] <= max:
    primeNum.append(seachList[0])
    tmp = seachList[0]
    seachList = [i for i in seachList if i % tmp != 0]
  primeNum.extend(seachList)
  return primeNum

#####GCD#####
def gcd(a, b):
    while b: a, b = b, a % b
    return a

#####LCM#####
def lcm(a, b):
    return a * b // gcd (a, b)

#####BitCount#####
def count_bit(n):
  count = 0
  while n:
    n &= n-1
    count += 1
  return count

#####ChangeBase#####
def base_10_to_n(X, n):
  if X//n: return base_10_to_n(X//n, n)+[X%n]
  return [X%n]

def base_n_to_10(X, n):
  return sum(int(str(X)[-i-1])*n**i for i in range(len(str(X))))

def base_10_to_n_without_0(X, n):
  X -= 1
  if X//n: return base_10_to_n_without_0(X//n, n)+[X%n]
  return [X%n]

#####IntLog#####
def int_log(n, a):
  count = 0
  while n>=a:
    n //= a
    count += 1
  return count

#############
# Main Code #
#############
N = I()
order = []
to = [[] for i in range(N)]

def bfs(graph, start):
  N = len(graph)
  d = [INF] * N
  d[start] = 0
  q = deque([start])
  while q:
    u = q.popleft()
    order.append(u)
    for v in graph[u]:
      if d[v] != INF: continue
      d[v] = d[u] + 1
      to[u].append(v)
      q.append(v)
  return d

graph = [[] for i in range(N)]
for _ in range(N-1):
  a,b = IL()
  graph[a-1].append(b-1)
  graph[b-1].append(a-1)
bfs(graph,0)

dp = [[0,0] for i in range(N)]

for i in order[::-1]:
  if not to[i]:
    dp[i] = [1,1]
  else:
    temp1 = 1
    temp2 = 1
    for j in to[i]:
      temp1 *= sum(dp[j])
      temp1 %= MOD
      temp2 *= dp[j][1]
      temp2 %= MOD
    dp[i] = [temp2%MOD,temp1%MOD]
print(sum(dp[0])%MOD)

Submission status: Accepted

Solution code:
from sys import stdin
import sys
import math
from functools import reduce
import functools
import itertools
from collections import deque,Counter,defaultdict
from operator import mul
import copy
# ! /usr/bin/env python
# -*- coding: utf-8 -*-
import heapq
sys.setrecursionlimit(10**6)
INF =  float("inf")
import bisect
import statistics
mod = 10**9+7

N = int(input())
al = [[] for i in range(N+1)]

for i in range(N-1):
    a, b = list(map(int, input().split()))

    al[a].append(b)
    al[b].append(a)

b = [0 for i in range(N + 1)]
w = [0 for i in range(N + 1)]
seen = [0 for i in range(N + 1)]

@functools.lru_cache(None)
def bfs(u):
    seen[u] = 1

    b[u] = 1
    w[u] = 1

    for v in al[u]:
        if seen[v] == 0:
            seen[v] = 1
            bfs(v)
            b[u] = (b[u] * w[v]) % mod
            w[u] = (w[u] * ((b[v] + w[v]) % mod)) % mod

bfs(1)

print((b[1] + w[1]) % mod)

Submission status: Accepted

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
from bisect import bisect_right, bisect_left
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, gamma, log
from operator import mul
from functools import reduce
from copy import deepcopy

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().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): pass
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 = 10 ** 9 + 7

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


par = [-1] * n
def f(u):
    b, w = 1, 1
    for v in G[u]:
        if v == par[u]:
            continue
        par[v] = u
        cb, cw = f(v)
        b = b * cw % mod
        w = w * (cw + cb)
    return b, w

bb, ww = f(0)
print((bb + ww) % mod)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys 
sys.setrecursionlimit(10**6)
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
MOD = 10**9+7
# 入力
N = int(readline())
edge = [[] for _ in range(N+1)]
for i in range(N-1):
    x,y = map(int,readline().split())
    edge[x].append(y)
    edge[y].append(x)

#dfs
#total すべての合計,white どの頂点を白としたときの合計 
def dfs(x,par):
    total,white = 1,1
    for y in edge[x]:
        if y == par:
            continue
        w,t = dfs(y,x)
        total *= w; total%=MOD
        white *= t; white%=MOD
    total += white
    total %= MOD
    return white,total

# 出力
print(dfs(1,0)[1])

Submission status: Accepted

Solution code:
import sys
readline = sys.stdin.readline
sys.setrecursionlimit(10 ** 5 + 1)

N = int(readline())
G = [[] for i in range(N)]

for i in range(N - 1):
  x,y = map(int,readline().split())
  G[x - 1].append(y - 1)
  G[y - 1].append(x - 1)

DIV = 10 ** 9 + 7

# 頂点iが白であるときの場合の数は、(iの子の白である場合 + 黒である場合)の数同士の積
# 頂点iが黒であるときの場合の数は、iの子が白である場合の数同士の積
# 自分の子が決まっていない場合は再帰的に探索する

# dp[i][j] = 頂点iがj(1:黒, 0:白)である場合の数
dp = [[-1] * 2 for i in range(N)]

def search_black(X, parent): # Xが黒の場合の数を求める
  if dp[X][1] != -1:
    return dp[X][1]
  # 自分に子供がいなければ、1を返す
  children = G[X]
  if len(children) == 1 and children[0] == parent:
    dp[X][1] = 1
    return 1
  ans = 1
  for child in children:
    if child == parent:
      continue
    ans *= search_white(child, X)
    ans %= DIV
  dp[X][1] = ans
  return ans
  
def search_white(X, parent): # Xが白の場合の数を求める
  if dp[X][0] != -1:
    return dp[X][0]
  # 自分に子供がいなければ、1を返す
  children = G[X]
  if len(children) == 1 and children[0] == parent:
    dp[X][0] = 1
    return 1
  ans = 1
  for child in children:
    if child == parent:
      continue
    ans *= (search_white(child, X) + search_black(child, X))
    ans %= DIV
  dp[X][0] = ans
  return ans
  
print((search_white(0, -1) + search_black(0, -1)) % DIV)

Submission status: Accepted

Solution code:
from sys import stdin, stdout, setrecursionlimit
from collections import deque, defaultdict, Counter
from heapq import heappush, heappop
from functools import lru_cache
import math

setrecursionlimit(10**6)
rl = lambda: stdin.readline()
rll = lambda: stdin.readline().split()
rli = lambda: map(int, stdin.readline().split())
rlf = lambda: map(float, stdin.readline().split())

INF, NINF = float('inf'), float('-inf')

def main():
	MOD = 10**9 + 7
	n = int(rl())
	G = [[] for _ in range(n)]
	for _ in range(n-1):
		u, v = rli()
		u -= 1
		v -= 1
		G[u].append(v)
		G[v].append(u)


	wb = [[1,1] for _ in range(n+1)]
	wb[n] = [0, 0]
	seen = [0 for _ in range(n)]
	stack = []
	stack.append((0, n))
	while stack:
		node, prnt = stack.pop()
		w, b = wb[node]
		if not seen[node]:
			seen[node] = 1
			stack.append((node, prnt))
			for nbhr in G[node]:
				if nbhr == prnt: continue
				stack.append((nbhr, node))
		else:
			pw, pb = wb[prnt]
			pw *= (w + b)
			pb *= w 
			wb[prnt] = [pw % MOD, pb % MOD]

	ans = (wb[0][0] + wb[0][1]) % MOD
	print(ans)
	stdout.close()

if __name__ == "__main__":
	main()

Submission status: Accepted

Solution code:
from sys import stdin, stdout, setrecursionlimit
from collections import deque, defaultdict, Counter
from heapq import heappush, heappop
from functools import lru_cache
import math

setrecursionlimit(10**6)
rl = lambda: stdin.readline()
rll = lambda: stdin.readline().split()
rli = lambda: map(int, stdin.readline().split())
rlf = lambda: map(float, stdin.readline().split())

INF, NINF = float('inf'), float('-inf')

def main():
	MOD = 10**9 + 7
	n = int(rl())
	G = [[] for _ in range(n)]
	for _ in range(n-1):
		u, v = rli()
		u -= 1
		v -= 1
		G[u].append(v)
		G[v].append(u)

	def dfs(node, prnt):
		w, b = 1, 1
		for nbhr in G[node]:
			if nbhr == prnt: continue
			nw, nb = dfs(nbhr, node)
			w *= (nw + nb)
			w %= MOD
			b *= nw 
			b %= MOD
		return w, b

	answ, ansb = dfs(0, -1)
	print((answ + ansb) % MOD)

	stdout.close()

if __name__ == "__main__":
	main()

Submission status: Accepted

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

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

def dfs(v,mod):
  black,white = 1,1
  for u in edge[v]:
    if visited[u]==False:
      visited[u]=True
      b,w = dfs(u,mod)
      black *= w
      white *= b+w
  black %= mod
  white %= mod
  return black,white

mod = 10**9+7
visited = [False]*N
visited[0]=True
black,white = dfs(0,mod)
print((black+white)%mod)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**7)
n=int(input())
if n==1:
    print(2)
    exit()
edge=[[] for _ in range(n)]
for _ in range(n-1):
    x,y=map(int,input().split())
    x-=1
    y-=1
    edge[x].append(y)
    edge[y].append(x)
dp=[[0]*2 for _ in range(n)]
mod=10**9+7
def dfs(s,prev):
    if edge[s]==[prev]:
        dp[s][0]=1
        dp[s][1]=1
        return
    w=1
    b=1
    for c in edge[s]:
        if c==prev:
            continue
        dfs(c,s)
        w=w*(dp[c][0]+dp[c][1])%mod
        b=b*dp[c][0]%mod
    dp[s][0]=w
    dp[s][1]=b
    return
dfs(0,-1)
print(sum(dp[0])%mod)

Submission status: Accepted

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

mod=10**9+7
def dfs(v):
  if checked[v]==1:
    return
  checked[v]=1
  dp[v][0]=1
  dp[v][1]=1
  for u in g[v]:
    if checked[u]==0:
      dfs(u)
      dp[v][0]=(dp[v][0]*(dp[u][0]+dp[u][1]))%mod
      dp[v][1]=(dp[v][1]*dp[u][0])%mod

n=int(input())
g=[[] for _ in range(n+1)]
for _ in range(n-1):
  a,b=map(int,input().split())
  g[a].append(b)
  g[b].append(a)
dp=[[0,0] for _ in range(n+1)]
checked=[0]*(n+1)
dfs(1)
print((dp[1][0]+dp[1][1])%mod)

Submission status: Accepted

Solution code:
import sys,bisect,string,math,time,functools,random,fractions
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
from itertools import permutations,combinations,groupby
rep=range;R=range
def Golf():n,*t=map(int,open(0).read().split())
def I():return int(input())
def S_():return input()
def IS():return input().split()
def LS():return [i for i in input().split()]
def MI():return map(int,input().split())
def LI():return [int(i) for i in input().split()]
def LI_():return [int(i)-1 for i in input().split()]
def NI(n):return [int(input()) for i in range(n)]
def NI_(n):return [int(input())-1 for i in range(n)]
def StoLI():return [ord(i)-97 for i in input()]
def ItoS(n):return chr(n+97)
def LtoS(ls):return ''.join([chr(i+97) for i in ls])
def RA():return map(int,open(0).read().split())
def GI(V,E,ls=None,Directed=False,index=1):
    org_inp=[];g=[[] for i in range(V)]
    FromStdin=True if ls==None else False
    for i in range(E):
        if FromStdin:
            inp=LI()
            org_inp.append(inp)
        else:
            inp=ls[i]
        if len(inp)==2:
            a,b=inp;c=1
        else:
            a,b,c=inp
        if index==1:a-=1;b-=1
        aa=(a,c);bb=(b,c);g[a].append(bb)
        if not Directed:g[b].append(aa)
    return g,org_inp
def GGI(h,w,search=None,replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1):
    #h,w,g,sg=GGI(h,w,search=['S','G'],replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1) # sample usage
    mp=[boundary]*(w+2);found={}
    for i in R(h):
        s=input()
        for char in search:
            if char in s:
                found[char]=((i+1)*(w+2)+s.index(char)+1)
                mp_def[char]=mp_def[replacement_of_found]
        mp+=[boundary]+[mp_def[j] for j in s]+[boundary]
    mp+=[boundary]*(w+2)
    return h+2,w+2,mp,found
def TI(n):return GI(n,n-1)
def accum(ls):
    rt=[0]
    for i in ls:rt+=[rt[-1]+i]
    return rt
def bit_combination(n,base=2):
    rt=[]
    for tb in R(base**n):s=[tb//(base**bt)%base for bt in R(n)];rt+=[s]
    return rt
def gcd(x,y):
    if y==0:return x
    if x%y==0:return y
    while x%y!=0:x,y=y,x%y
    return y
def YN(x):print(['NO','YES'][x])
def Yn(x):print(['No','Yes'][x])
def show(*inp,end='\n'):
    if show_flg:print(*inp,end=end)

mo=10**9+7
inf=float('inf')
FourNb=[(-1,0),(1,0),(0,1),(0,-1)];EightNb=[(-1,0),(1,0),(0,1),(0,-1),(1,1),(-1,-1),(1,-1),(-1,1)];compas=dict(zip('WENS',FourNb));cursol=dict(zip('LRUD',FourNb))
l_alp=string.ascii_lowercase
#sys.setrecursionlimit(10**7)
read=sys.stdin.buffer.read;readline=sys.stdin.buffer.readline;input=lambda:sys.stdin.readline().rstrip()

########################################################################################################################################################################
# Verified by 
# https://atcoder.jp/contests/abc014/tasks/abc014_4
# https://atcoder.jp/contests/abc133/tasks/abc133_f

# import SparseTable
# initialize
# Tree() => n; (a,b);*(n-1)
# Tree(n) => (a,b);*(n-1)
# Tree(init=False); Tree.stdin(); => n; (a,b);*(n-1)
# Tree(init=False); Tree.listin(ls,index=0); => (a,b);*(n-1)

import sys,bisect,string,math,time,functools,random,fractions
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
from itertools import permutations,combinations,groupby
rep=range
def Golf():n,*t=map(int,open(0).read().split())
def I():return int(input())
def S_():return input()
def IS():return input().split()
def LS():return [i for i in input().split()]
def MI():return map(int,input().split())
def LI():return [int(i) for i in input().split()]
def LI_():return [int(i)-1 for i in input().split()]
def NI(n):return [int(input()) for i in range(n)]
def NI_(n):return [int(input())-1 for i in range(n)]
def StoLI():return [ord(i)-97 for i in input()]
def ItoS(n):return chr(n+97)
def LtoS(ls):return ''.join([chr(i+97) for i in ls])
def RA():return map(int,open(0).read().split())
def GI(V,E,ls=None,Directed=False,index=1):
    org_inp=[];g=[[] for i in range(V)]
    FromStdin=True if ls==None else False
    for i in range(E):
        if FromStdin:
            inp=LI()
            org_inp.append(inp)
        else:
            inp=ls[i]
        if len(inp)==2:
            a,b=inp;c=1
        else:
            a,b,c=inp
        if index==1:a-=1;b-=1
        aa=(a,c);bb=(b,c);g[a].append(bb)
        if not Directed:g[b].append(aa)
    return g,org_inp
def GGI(h,w,search=None,replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1):
    #h,w,g,sg=GGI(h,w,search=['S','G'],replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1) # sample usage
    mp=[boundary]*(w+2);found={}
    for i in range(h):
        s=input()
        for char in search:
            if char in s:
                found[char]=((i+1)*(w+2)+s.index(char)+1)
                mp_def[char]=mp_def[replacement_of_found]
        mp+=[boundary]+[mp_def[j] for j in s]+[boundary]
    mp+=[boundary]*(w+2)
    return h+2,w+2,mp,found
def TI(n):return GI(n,n-1)
def accum(ls):
    rt=[0]
    for i in ls:rt+=[rt[-1]+i]
    return rt
def bit_combination(n,base=2):
    rt=[]
    for tb in range(base**n):s=[tb//(base**bt)%base for bt in range(n)];rt+=[s]
    return rt
def gcd(x,y):
    if y==0:return x
    if x%y==0:return y
    while x%y!=0:x,y=y,x%y
    return y
def YN(x):print(['NO','YES'][x])
def Yn(x):print(['No','Yes'][x])
def show(*inp,end='\n'):
    if show_flg:print(*inp,end=end)

mo=10**9+7
inf=float('inf')
FourNb=[(-1,0),(1,0),(0,1),(0,-1)];EightNb=[(-1,0),(1,0),(0,1),(0,-1),(1,1),(-1,-1),(1,-1),(-1,1)];compas=dict(zip('WENS',FourNb));cursol=dict(zip('LRUD',FourNb))
l_alp=string.ascii_lowercase
#sys.setrecursionlimit(10**7)
read=sys.stdin.buffer.read
readline=sys.stdin.buffer.readline
input=lambda: sys.stdin.readline().rstrip()

class Tree:
    def __init__(self,inp_size=None,ls=None,init=True,index=1):
        self.LCA_init_stat=False
        self.ETtable=[]
        if init:
            if ls==None:
                self.stdin(inp_size,index=index)
            else:
                self.node_size=len(ls)+1
                self.edges,_=GI(self.node_size,self.node_size-1,ls,index=index)
        return
 
    def stdin(self,inp_size=None,index=1):
        if inp_size==None:
            self.node_size=int(input())
        else:
            self.node_size=inp_size
        self.edges,_=GI(self.node_size,self.node_size-1,index=index)
        return
    
    def listin(self,ls,index=0):
        self.node_size=len(ls)+1
        self.edges,_=GI(self.node_size,self.node_size-1,ls,index=index)
        return
 
    def dfs(self,x,func=lambda pr,prv,nx,dist:prv+dist,root_v=0):
        q=deque([x])
        v=[None]*self.node_size
        v[x]=root_v
        while q:
            c=q.pop()
            for nb,d in self.edges[c]:
                if v[nb]==None:
                    q.append(nb)
                    v[nb]=func(c,v[c],nb,d)
        return v
 
    def bfs(self,x,func=lambda pr,prv,nx,dist:prv+dist,root_v=0):
        q=deque([x])
        v=[None]*self.node_size
        v[x]=root_v
        while q:
            c=q.popleft()
            for nb,d in self.edges[c]:
                if v[nb]==None:
                    q.append(nb)
                    v[nb]=func(c,v[c],nb,d)
        return v
 
    def parent(self,x):
        return self.dfs(0,func=lambda pr,prv,nx,dist:pr,root_v=-1)
 
    def topological_sort(self,x):  # return topological sort of the tree
        tps=[]
        q=deque([x])
        v=[None]*self.node_size
        v[x]=0
        while q:
            c=q.popleft()
            tps.append(c)
            for nb,d in self.edges[c]:
                if v[nb]==None:
                    q.append(nb)
                    v[nb]=0
        return tps
 
    def EulerTour(self,x):
        q=deque()
        q.append(x)
        self.depth=[None]*self.node_size
        self.depth[x]=0
        self.ETtable=[]
        self.ETdepth=[]
        self.ETin=[-1]*self.node_size
        self.ETout=[-1]*self.node_size
        cnt=0
        while q:
            c=q.pop()
            if c<0:
                ce=~c
            else:
                ce=c
                for nb,d in self.edges[ce]:
                    if self.depth[nb]==None:
                        q.append(~ce)
                        q.append(nb)
                        self.depth[nb]=self.depth[ce]+1
            self.ETtable.append(ce)
            self.ETdepth.append(self.depth[ce])
            if self.ETin[ce]==-1:
                self.ETin[ce]=cnt
            else:
                self.ETout[ce]=cnt
            cnt+=1
        return
    
    def doubling_LCA(self,root,x,y):
        if self.LCA_init_stat==False:
            self.depth=[None]*self.node_size
            self.depth=self.bfs(0,func=lambda pr,prv,nxt,dist:prv+1)
            self.par=self.bfs(0,func=lambda pr,prv,nxt,dist:pr)
            self.db=[self.par]
            for i in range(self.node_size.bit_length()):
                #show(self.db)
                self.db+=[[self.db[-1][self.db[-1][i]] for i in range(self.node_size)]]
            self.LCA_init_stat=True
        dx=self.depth[x]
        dy=self.depth[y]
        if dx>dy:
            dx,dy=dy,dx
        c=self.node_size.bit_length()
        while c>0:
            if dx+c<=dy:
                x=self.db[c][x]
                dx+=1<<c
            c>>=1
        
        if x==y:
            return x
        
        c=self.node_size.bit_length()
        while c>0:
            if self.db[c][x]!=self.db[c][y]:
                x=self.db[c][x]
                y=self.db[c][y]
            c>>=1
        
        return self.par[x]
        
    def LCA_init(self,root):
        self.EulerTour(root)
        self.st=SparseTable(self.ETdepth,init_func=min,init_idl=inf)
        #self.st=SegTree(self.node_size*2-1,self.ETdepth,function=min,ide=inf)
        self.LCA_init_stat=True
        return
    
    def LCA(self,root,x,y):
        if self.LCA_init_stat==False:
            self.LCA_init(root)
        xin,xout=self.ETin[x],self.ETout[x]
        yin,yout=self.ETin[y],self.ETout[y]
        a=min(xin,yin)
        b=max(xout,yout,xin,yin)
        id_of_min_dep_in_et=self.st.query_id(a,b+1)
        return self.ETtable[id_of_min_dep_in_et]
 
    def __str__(self):
        return  str(self.edges)
 
    def show(self):
        if all([all([d==1 for nd,d in e]) for e in self.edges]):
            print( [[nd for nd,d in e] for e in self.edges] )
        else:
            print(self)
 
    def dfs2(self,x,func=lambda pr,prv,nx,dist:prv+dist,root_v=0):
        q=deque([x])
        v=[None]*self.node_size
        v[x]=root_v
        dfs_tr=[x]
        while q:
            c=q.pop()
            for nb,d in self.edges[c]:
                if v[nb]==None:
                    q.append(nb)
                    v[nb]=func(c,v[c],nb,d)
                    dfs_tr+=nb,
        return v,dfs_tr

show_flg=False
show_flg=True

ans=0
n=I()
if n==1:print(2);exit()
tr=Tree(n)
v,root=tr.dfs2(0)
p=tr.parent(0)
x=[[1,1]for i in range(n)]
for c in root[::-1]:
        
    x[p[c]][0]*=sum(x[c])
    x[p[c]][1]*=x[c][0]
    x[p[c]][0]%=mo
    x[p[c]][1]%=mo
    
print(sum(x[0])%mo)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

n = int(input())
C = [list(map(int,input().split())) for i in range(n-1)]
mod = 10**9 + 7

for i in range(n-1):
    for j in range(2):
        C[i][j] -= 1

ans = 0
M = [[] for i in range(n)]
for i in range(n-1):
    M[C[i][0]].append(C[i][1])
    M[C[i][1]].append(C[i][0])

D = [[1,1] for i in range(n)]
MN = [len(M[i]) for i in range(n)]
# print("MN", MN)

V = [0] * n
Q = []
for i in range(1, n):
    if MN[i] == 1:
        Q.append(i)
        V[i] = 1

# print(Q)

s = 0
while s < len(Q):
    x = Q[s]
    for y in M[x]:
        if V[y] == 0:
            # print("y",y)
            D[y][0] = (D[y][0] * sum(D[x])) % mod
            D[y][1] = (D[y][1] * D[x][0]) % mod
            MN[y] -= 1
            if (y != 0 and MN[y] == 1) or (y == 0 and MN[y] == 0):
                V[y] = 1
                Q.append(y)
    s += 1

print(sum(D[0]) % mod)

Submission status: Accepted

Solution code:
import sys
from collections import deque
stdin = sys.stdin


def ni(): return int(ns())


def na(): return list(map(int, stdin.readline().split()))


def naa(N): return [na() for _ in range(N)]


def ns(): return stdin.readline().rstrip()  # ignore trailing spaces


def make_tree_0index(N):
    edge_dic = {}
    for _ in range(N-1):
        x, y = na()
        x -= 1
        y -= 1
        if x in edge_dic:
            edge_dic[x].append(y)
        else:
            edge_dic[x] = [y]
        if y in edge_dic:
            edge_dic[y].append(x)
        else:
            edge_dic[y] = [x]
    return edge_dic


N = ni()
if N == 1:
    print(2)
    exit()
edge_dic = make_tree_0index(N)
ans = [[0] * 2 for _ in range(N)]
mod = 10 ** 9 + 7

parent_array = [-2] * N
parent_array[0] = -1
node1 = deque([0])
node2 = deque([0])

while(len(node1)):
    n = node1.popleft()
    for v in edge_dic[n]:
        if parent_array[v] == -2:
            parent_array[v] = n
            node1.append(v)
            node2.append(v)

while(len(node2)):
    n = node2.pop()
    white = 1
    black = 1
    for v in edge_dic[n]:
        if parent_array[n] == v:
            continue
        white = (white * (ans[v][0] + ans[v][1])) % mod
        black = black * ans[v][0] % mod
    ans[n][0] = white
    ans[n][1] = black


print((ans[0][0] + ans[0][1]) % mod)

Submission status: Accepted

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

MOD = 10 ** 9 + 7
def dfs(v, pv):
    white, black = 1, 1
    for nv in edge[v]:
        if nv == pv: continue
        rw, rb = dfs(nv, v)
        white *= rw + rb
        white %= MOD
        black *= rw
        black %= MOD
    return white, black

N = int(input())
edge = [[] for _ in range(N)]

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

print(sum(dfs(0, -1)) % MOD)

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import accumulate, permutations, combinations, product, islice
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce, lru_cache
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10**9 + 7

N = INT()
xy = [LIST() for _ in range(N-1)]
tree = [[] for _ in range(N)]
for x, y in xy:
    tree[x-1].append(y-1)
    tree[y-1].append(x-1)

def rec(n, par):
    f, g = 1, 1
    for node in tree[n]:
        if node == par:
            continue
        fn, gn = rec(node, n)
        f *= gn
        f %= mod
        g *= fn
        g %= mod
 
    return (f+g)%mod, g
 
print(rec(0, None)[0])

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import accumulate, permutations, combinations, product, islice
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce, lru_cache
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10**9 + 7

N = INT()
xy = [LIST() for _ in range(N-1)]
tree = [[] for _ in range(N)]
for x, y in xy:
    tree[x-1].append(y-1)
    tree[y-1].append(x-1)

@lru_cache(maxsize=None)
def DFS(i, par, c):  # c:0->white, 1->black
    if par and len(tree[i]) == 1:
        return 1
    if c == 0:
        cnt = 1
        for node in tree[i]:
            if node != par:
                cnt *= (DFS(node, i, 0) + DFS(node, i, 1))
                cnt %= mod
        return cnt
    elif c == 1:
        cnt = 1
        for node in tree[i]:
            if node != par:
                cnt *= DFS(node, i, 0)
                cnt %= mod
        return cnt

ans = DFS(0, None, 0)+DFS(0, None, 1)
print(ans%mod)

Submission status: Accepted

Solution code:
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


n = int(input())
ns = [[] for _ in range(n)]
for i in range(n-1):
    u,v = map(int, input().split())
    u -= 1
    v -= 1
    ns[u].append(v)
    ns[v].append(u)

d1 = [None]*n
d2 = [None]*n
M = 10**9+7
def sub(u, p):
    if d1[u] is not None:
        return d1[u], d2[u]
    v1 = 1 # 白
    v2 = 1 # 黒
    for v in ns[u]:
        if v==p:
            continue
        w1, w2 = sub(v, u)
        v1 *= (w1+w2)
        v2 *= w1
        v1 %= M
        v2 %= M
    d1[u] = v1
    d2[u] = v2
    return v1, v2
sub(0, -1)
print((d1[0]+d2[0])%M)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10 ** 7)
mod = 10 ** 9 + 7

def memodp(DPW, DPB, near, x, FLAG):
    if DPW[x] + DPB[x] > 2:
        return (DPB[x] + DPW[x]) % mod
    else:
        for i in near[x]:
            if i not in FLAG:
                FLAG.add(i)
                DPW[x] *= memodp(DPW, DPB, near, i, FLAG)
                DPB[x] *= DPW[i]
        DPW[x], DPB[x] = DPW[x] % mod, DPB[x] % mod
        return (DPW[x] + DPB[x]) % mod


n = int(input())
xy = [list(map(int, input().split())) for i in range(n - 1)]

near = [[] for _ in range(n)]
for x, y in xy:
    near[x - 1].append(y - 1)
    near[y - 1].append(x - 1)

dpw, dpb, flag = [1] * n, [1] * n, set([0])
print(memodp(dpw, dpb, near, 0, flag))