Problem:


Score : 1000 points

Problem Statement

Snuke has a rooted tree with N+1 vertices.
The vertices are numbered 0 through N, and Vertex 0 is the root of the tree.
The parent of Vertex i (1 \leq i \leq N) is Vertex p_i.

Besides this tree, Snuke also has an box which is initially empty and many marbles, and playing with them.
The play begins with placing one marble on some of the vertices, then proceeds as follows:

If there is a marble on Vertex 0, move the marble into the box.

Move each marble from the vertex to its parent (all at once).

For each vertex occupied by two or more marbles, remove all the marbles from the vertex.

If there exists a vertex with some marbles, go to Step 1. Otherwise, end the play.

There are 2^{N+1} ways to place marbles on some of the vertices.
For each of them, find the number of marbles that will be in the box at the end of the play, and compute the sum of all those numbers modulo 1,000,000,007.

Constraints

1 \leq N < 2 \times 10^{5}

0 \leq p_i < i

Partial Scores

In the test set worth 400 points, N < 2{,}000.

Input

Input is given from Standard Input in the following format:

N
p_1 p_2 ... p_{N}

Output

Print the answer.

Sample Input 1

2
0 0

Sample Output 1

8

When we place a marble on both Vertex 1 and 2, there will be multiple marbles on Vertex 0 by step 2. In such a case, these marbles will be removed instead of being moved to the box.

Sample Input 2

5
0 1 1 0 4

Sample Output 2

96

Sample Input 3

31
0 1 0 2 4 0 4 1 6 4 3 9 7 3 7 2 15 6 12 10 12 16 5 3 20 1 25 20 23 24 23

Sample Output 3

730395550

Be sure to compute the sum modulo 1,000,000,007.



Sample input:
2
0 0


Sample output:
8

Submission status: Accepted

Solution code:

"""

https://atcoder.jp/contests/arc086/tasks/arc086_c

対消滅する可能性があるのは同じ深さの点に置かれたビー玉だけ
→1つも残らない or 1つだけ残るである

すなわち、ある深さに関して、そのうち1つ残るのがいくつあるかを数えればよい

1つだけ置く場合→絶対のこる
2つ置く場合→絶対消える
3つ置く場合→3つのLCAが等しくなければ残る

木dpみたいにする？
dp[0] = 一つも含んでいない場合の通り数
dp[1] = 1つ含んでいる場合の通り数

dp[0] = すべての場合 - dp[1]
dp[1] = 1つだけ1を持っている場合

で、子から親に伝播させていく…？
マージテクで計算量削減か？
3sだからそうっぽいな…
3つ以上のマージ書くのだるすぎん？

またはマージの順番をどっかにメモっておく

maxd-d = indexでやる
最長のやつにマージする

dp[maxd-d][1] = 1つだけ元深さdが残っている場合の数
c = 子の数

計算量は？
サイズは高々1しか増えないので可能っぽい
2倍処理がまずい

もっと簡潔に？
単一のdだけで考えよう
2倍処理なんてしない
最後に各dに関してかければいい
→するとマージの際に2番目の大きさだけでなんとかなる

必要のないマージをしない
両方に関係ないdは操作しない
むしろばらつきは深い部分にだけ存在するか
浅い部分は共通。よって-xで管理すればいいか

"""

import sys
mod = 10**9 + 7
sys.setrecursionlimit(200000)

from collections import deque
def NC_Dij(lis,start):

    ret = [float("inf")] * len(lis)
    ret[start] = 0
    
    q = deque([start])
    plis = [i for i in range(len(lis))]

    while len(q) > 0:
        now = q.popleft()

        for nex in lis[now]:

            if ret[nex] > ret[now] + 1:
                ret[nex] = ret[now] + 1
                plis[nex] = now
                q.append(nex)

    return ret,plis

def inverse(a): #aのmodを法にした逆元を返す
    return pow(a,mod-2,mod)


def dfs(v):

    if len(lis[v]) == 0:
        ret = [ [1,1] ]
        return ret

    else:

        retlis = []
        for nex in lis[v]:
            nret = dfs(nex)
            retlis.append( [len(nret),nret] )
        retlis.sort()

        #1つしかない場合マージしない
        if len(retlis) == 1:
            retlis[-1][1].append([1,1])
            return retlis[-1][1]

        #2つ以上の場合最大のやつにマージする
        for revd in range(retlis[-2][0]):

            zmul = 1
            amul = 1
            for i in range(len(retlis)-1,-1,-1):
                if revd < retlis[i][0]:
                    zmul *= retlis[i][1][-1-revd][0]
                    amul *= sum(retlis[i][1][-1-revd])
                    zmul %= mod
                    amul %= mod
                else:
                    break

            nsum = 0
            for i in range(len(retlis)-1,-1,-1):
                if revd < retlis[i][0]:
                    nsum += zmul * inverse(retlis[i][1][-1-revd][0]) * retlis[i][1][-1-revd][1]
                    nsum %= mod
                else:
                    break

            retlis[-1][1][-1-revd][1] = nsum
            retlis[-1][1][-1-revd][0] = (amul-nsum) % mod

        retlis[-1][1].append([1,1])
        return retlis[-1][1]

N = int(input())
p = list(map(int,input().split()))

lis = [ [] for i in range(N+1) ]

for i in range(N):

    #lis[i+1].append(p[i])
    lis[p[i]].append(i+1)

dlis,plis = NC_Dij(lis,0)
maxd = max(dlis)

dn = [0] * (maxd+1)
for i in dlis:
    dn[i] += 1

ans = dfs(0)
#print (dn,ans)
A = 0
for i in range(maxd+1):
    A += ans[-1-i][1] * pow(2,N+1-dn[i],mod)
    A %= mod
print (A)

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10 ** 6)
input = sys.stdin.readline
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")

def main():
    def dfs(u=0):
        def merge(dpu, dpv):
            vn = len(dpv)
            for d in range(-1, -1 - vn, -1):
                u0, u1, u2 = dpu[d]
                v0, v1, v2 = dpv[d]
                n0 = (u0 * v0) % md
                n1 = (u0 * v1 + u1 * v0) % md
                n2 = (u2 * (v0 + v1 + v2) + v2 * (u0 + u1) + u1 * v1) % md
                dpu[d] = (n0, n1, n2)

        # 葉の場合
        if len(to[u]) == 0:
            return [(inv2, inv2, 0)]
        # すべての子をマージ
        dpu = []
        mxlen=0
        for v in to[u]:
            dpv = dfs(v)
            #深さが2段以上あったらu2をu0に
            if not dpu:
                dpu = dpv
            else:
                if len(dpu) < len(dpv): dpu, dpv = dpv, dpu
                mxlen=max(mxlen,len(dpv))
                merge(dpu, dpv)
        for d in range(-1,-1-mxlen,-1):
            u0,u1,u2=dpu[d]
            dpu[d] = (u0 + u2, u1, 0)
        dpu.append((inv2, inv2, 0))
        return dpu

    md = 10 ** 9 + 7
    # 1/2のmod
    inv2 = pow(2, md - 2, md)
    n = int(input())
    to = [[] for _ in range(n+1)]
    pp = list(map(int, input().split()))
    for i, p in enumerate(pp, 1):
        to[p].append(i)
    # print(to)
    dp0 = dfs()
    # print(dp0)
    ans = sum(u1 for _, u1, _ in dp0)
    print((ans * pow(2, n + 1, md)) % md)

main()

Submission status: Accepted

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

MOD = 10 ** 9 + 7

N = int(input())
graph = [[] for _ in range(N+1)]
for i,x in enumerate(input().rstrip().split(),1):
    x = int(x)
    graph[i].append(x)
    graph[x].append(i)

# 各深さから来ている (0個、1個、2個以上) の分布を 確率 mod MODで持つ。

half = (MOD + 1) // 2

def merge(dp,dp1):
    L = len(dp1)
    for i in range(L):
        # 0個,1個,2個以上
        a,b,c = dp[i]
        d,e,f = dp1[i]
        a,b,c = a*d, a*e + b*d, a*f + b*e + b*f + c*d + c*e + c*f
        a %= MOD
        b %= MOD
        c %= MOD
        dp[i] = (a,b,c)
    return

def dfs(v,parent = None):
    dp = None
    L = 0
    for u in graph[v]:
        if u == parent:
            continue
        dp1 = dfs(u,v)
        if dp is None:
            dp = dp1
        else:
            if len(dp) < len(dp1):
                dp,dp1 = dp1,dp
            # 2個以上が入っているインデックス
            if L < len(dp1):
                L = len(dp1)
            merge(dp,dp1)
    if dp is None:
        dp = deque()
    else:
        # 2個以上あるときに、0個化する
        for i in range(L):
            a,b,c = dp[i]
            dp[i] = (a+c,b,0)
    dp.appendleft((half,half,0))
    return dp

dp = dfs(0)

answer = sum(b for a,b,c in dp)
answer *= pow(2,N+1,MOD)
answer %= MOD
print(answer)

Submission status: Accepted

Solution code:
# seishin.py
from collections import deque
N = int(input())
*P, = map(int, input().split())
MOD = 10**9 + 7

G = [[] for i in range(N+1)]
U = [0]*(N+1)
C = [0]*(N+1)
for i, p in enumerate(P):
    G[p].append(i+1)
    U[i+1] = u = U[p]+1
    C[u] += 1
Q = [None]*(N+1)
PP = {}
def pp(k):
    if k not in PP:
        PP[k] = p = pow(2, k, MOD)
        return p
    return PP[k]
L = [0]*(N+1)

ept = []
sz = L.__getitem__
for i in range(N, -1, -1):
    g = G[i]
    if not g:
        continue

    # 子ノードのdequeを集める
    g.sort(key=sz, reverse=1)
    k = len(g)
    e = [pp(k) - k, k, 0]

    g0 = g[0]
    L[i] = L[g0] + 1
    if L[g0] == 0:
        Q[i] = deque([e])
        continue
    Q[i] = R = Q[g0]
    if k > 1:
        # a0 <- a2
        for s, r in zip(Q[g[1]] or ept, R):
            r[0] += r[2]; r[2] = 0

        for j in g[1:]:
            S = Q[j]
            if not S:
                break

            # dequeの小さい方から大きい方へマージする処理
            for (a0, a1, a2), r in zip(S, R):
                b0, b1, b2 = r; a0 += a2
                r[0] = a0*b0 % MOD
                r[1] = (a0*b1 + a1*b0) % MOD
                r[2] = ((a0+a1)*b2 + a1*b1) % MOD
    R.appendleft(e)
print((pp(N) + sum(pp(N+1-c) * a1 % MOD for (a0, a1, a2), c in zip(Q[0], C[1:]))) % MOD)

Submission status: Accepted

Solution code:
# seishin.py
from collections import deque
N = int(input())
*P, = map(int, input().split())
MOD = 10**9 + 7

G = [[] for i in range(N+1)]
U = [0]*(N+1)
C = [0]*(N+1)
for i, p in enumerate(P):
    G[p].append(i+1)
    U[i+1] = u = U[p]+1
    C[u] += 1
Q = [None]*(N+1)
PP = {}
def pp(k):
    if k not in PP:
        PP[k] = p = pow(2, k, MOD)
        return p
    return PP[k]
L = [0]*(N+1)

ept = []
sz = L.__getitem__
for i in range(N, -1, -1):
    g = G[i]
    if not g:
        continue

    # 子ノードのdequeを集める
    g.sort(key=sz, reverse=1)
    k = len(g)
    e = [pp(k) - k, k, 0]

    g0 = g[0]
    L[i] = L[g0] + 1
    if L[g0] == 0:
        Q[i] = deque([e])
        continue
    Q[i] = R = Q[g0]
    if k > 1:
        # a0 <- a2
        for s, r in zip(Q[g[1]] or ept, R):
            r[0] += r[2]; r[2] = 0

        for j in g[1:]:
            S = Q[j]
            if not S:
                break

            # dequeの小さい方から大きい方へマージする処理
            for (a0, a1, a2), r in zip(S, R):
                b0, b1, b2 = r; a0 += a2
                r[0] = a0*b0 % MOD
                r[1] = (a0*b1 + a1*b0) % MOD
                r[2] = ((a0+a1)*b2 + a1*b1) % MOD
    R.appendleft(e)
print((pp(N) + sum(pp(N+1-c) * a1 % MOD for (a0, a1, a2), c in zip(Q[0], C[1:]))) % MOD)

Submission status: Accepted

Solution code:
from collections import deque


def get_pow():
    cache = {}

    def func(x):
        if x not in cache:
            cache[x] = pow(2, x, mod)
        return cache[x]

    return func


mod = 1000000007
n = int(input())
parents = list(map(int, input().split()))
children = [set() for _ in range(n + 1)]
for c, p in enumerate(parents):
    children[p].add(c + 1)

levels = [{0}]
while True:
    level = set()
    for p in levels[-1]:
        level.update(children[p])
    if not level:
        break
    levels.append(level)
levels.reverse()

level_node_count = []
balls = [None] * (n + 1)

for i, level in enumerate(levels):
    level_node_count.append(len(level))
    for node in level:
        cn = children[node]
        if cn:
            if len(cn) == 1:
                bs = balls[cn.pop()]
                bs.appendleft([1, 1, 0])
                balls[node] = bs
                continue
            balls_from_children = [balls[c] for c in children[node]]
            balls_from_children.sort(key=len)
            bs1 = balls_from_children[0]
            for bs2 in balls_from_children[1:]:
                for (b10, b11, b12), b2 in zip(bs1, bs2):
                    b2[2] = ((b11 + b12) * b2[1] + b12 * b2[0]) % mod
                    b2[1] = (b10 * b2[1] + b11 * b2[0]) % mod
                    b2[0] = b2[0] * b10 % mod
                bs1 = bs2
            lim = len(balls_from_children[-2])
            for i, b in enumerate(bs1):
                if i >= lim:
                    break
                b[0] = (b[0] + b[2]) % mod
                b[2] = 0
            bs1.appendleft([1, 1, 0])
            balls[node] = bs1
        else:
            balls[node] = deque([[1, 1, 0]])

level_node_count.reverse()

pow2 = get_pow()
print(sum(b[1] * pow2(n - l + 1) % mod for l, b in zip(level_node_count, balls[0])) % mod)

Submission status: Accepted

Solution code:
from collections import deque


def get_pow():
    cache = {}

    def func(x):
        if x not in cache:
            cache[x] = pow(2, x, mod)
        return cache[x]

    return func


mod = 1000000007
n = int(input())
parents = list(map(int, input().split()))
children = [set() for _ in range(n + 1)]
for c, p in enumerate(parents):
    children[p].add(c + 1)

levels = [{0}]
while True:
    level = set()
    for p in levels[-1]:
        level.update(children[p])
    if not level:
        break
    levels.append(level)
levels.reverse()

level_node_count = []
balls = [None] * (n + 1)

for i, level in enumerate(levels):
    level_node_count.append(len(level))
    for node in level:
        cn = children[node]
        if cn:
            if len(cn) == 1:
                bs = balls[cn.pop()]
                bs.appendleft([1, 1, 0])
                balls[node] = bs
                continue
            balls_from_children = [balls[c] for c in children[node]]
            balls_from_children.sort(key=len)
            bs1 = balls_from_children[0]
            for bs2 in balls_from_children[1:]:
                for (b10, b11, b12), b2 in zip(bs1, bs2):
                    b2[2] = ((b11 + b12) * b2[1] + b12 * b2[0]) % mod
                    b2[1] = (b10 * b2[1] + b11 * b2[0]) % mod
                    b2[0] = b2[0] * b10 % mod
                bs1 = bs2
            for b in bs1:
                b[0] = (b[0] + b[2]) % mod
                b[2] = 0
            bs1.appendleft([1, 1, 0])
            balls[node] = bs1
        else:
            balls[node] = deque([[1, 1, 0]])

level_node_count.reverse()

pow2 = get_pow()
print(sum(b[1] * pow2(n - l + 1) % mod for l, b in zip(level_node_count, balls[0])) % mod)

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
a = list(map(int, input().split()))
cnt = {}

for i in a:
    if i in cnt.keys():
        cnt[i] += 1
    else:
        cnt[i] = 1

cnt = sorted(cnt.items(), key=lambda x: x[1])

ans, k = 0, k - len(cnt)
for i in range(len(cnt) + 1):
    if 0 <= k:
        print(ans)
        break
    ans += cnt[i]
    k -= 1

Submission status: Runtime Error

Solution code:
import sys
from collections import *

sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")

def main():
    def dfs(u=0):
        if not to[u]:
            dp[u] = [[0.5, 0.5, 0]]
            return
        dpu = []
        for v in to[u]:
            dfs(v)
            v = utou[v]
            if not dpu:
                dpu = dp[v]
                utou[u] = v
                continue
            dpv = dp[v]
            if len(dpu) < len(dpv):
                dpu, dpv = dpv, dpu
                utou[u] = v
            for d in range(len(dpv)):
                dpu[d][2] = dpu[d][2]*sum(dpv[d])+dpv[d][2]*sum(dpu[d])-dpu[d][2]*dpv[d][2]+dpu[d][1]*dpv[d][1]
                dpu[d][1] = dpu[d][0] * dpv[d][1] + dpu[d][1] * dpv[d][0]
                dpu[d][0] = dpu[d][0] * dpv[d][0]
        for d in range(len(dpu)):
            dpu[d][0] += dpu[d][2]
            dpu[d][2] = 0
        dpu.insert(0, [0.5, 0.5, 0])

    md=10**9+7
    to = defaultdict(list)
    n = int(input())
    pp = list(map(int, input().split()))
    for i, p in enumerate(pp):
        i += 1
        to[p].append(i)
    #print(to)
    utou = list(range(n + 1))
    dp = [[] for _ in range(n + 1)]
    dfs()
    #p2D(dp)
    #print(utou)
    root=utou[0]
    ans=0
    for dpr in dp[root]:
        ans+=dpr[1]
    print(int(pow(2,n+1)*ans)%md)


main()

Submission status: Runtime Error

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

MOD = 10 ** 9 + 7

N = int(input())
graph = [[] for _ in range(N+1)]
for i,x in enumerate(input().rstrip().split(),1):
    x = int(x)
    graph[i].append(x)
    graph[x].append(i)

# 各深さから来ている (0個、1個、2個以上) の分布を 確率 mod MODで持つ。

half = (MOD + 1) // 2

def merge(dp,dp1):
    L = len(dp1)
    for i in range(L):
        # 0個,1個,2個以上
        a,b,c = dp[i]
        d,e,f = dp1[i]
        a,b,c = a*d, a*e + b*d, a*f + b*e + b*f + c*d + c*e + c*f
        a %= MOD
        b %= MOD
        c %= MOD
        dp[i] = (a,b,c)
    return

def dfs(v,parent = None):
    dp = None
    L = 0
    for u in graph[v]:
        if u == parent:
            continue
        dp1 = dfs(u,v)
        if dp is None:
            dp = dp1
        else:
            if len(dp) < len(dp1):
                dp,dp1 = dp1,dp
            # 2個以上が入っているインデックス
            if L < len(dp1):
                L = len(dp1)
            merge(dp,dp1)
    if dp is None:
        dp = deque()
    else:
        # 2個以上あるときに、0個化する
        for i in range(L):
            a,b,c = dp[i]
            dp[i] = (a+c,b,0)
    dp.appendleft((half,half,0))
    return dp

dp = dfs(0)

answer = sum(b for a,b,c in dp)
answer *= pow(2,N+1,MOD)
answer %= MOD
print(answer)

Submission status: Runtime Error

Solution code:
import sys
import functools
import operator
readline = sys.stdin.readline

N = int(input())

P = [-1 for _ in range(N + 1)]
C = [[] for _ in range(N + 1)]
for i, p in enumerate(input().split()):
    P[i + 1] = int(p)
    C[int(p)].append(i + 1)

D = [[] for _ in range(N + 1)]
D[0].append(0)

ans = 0
for depth in range(N + 1):
    if len(D[depth]) == 0:
        break
    dp = [[0 for i in range(2)] for j in range(N + 1)]
    num = [0 for i in range(N + 1)]
    for d in range(depth, -1, -1):
        for i in D[d]:
            if d == depth:
                D[depth + 1] += C[i]
                dp[i][1] = 1
                dp[i][0] = 1
                num[i] = 1
            elif len(C[i]) == 0:
                dp[i][1] = 0
                dp[i][0] = 1
                num[i] = 0
            else:
                dp[i][1] = 0
                base = 1
                for j in C[i]:
                    base *= dp[j][0]
                for j in C[i]:
                    dp[i][1] += base * dp[j][1] // dp[j][0]
                    num[i] += num[j]
                dp[i][0] = 2 ** num[i] - dp[i][1]
    ans += (dp[0][1] * (2 ** (N + 1 - len(D[depth])))) % 1000000007

print(ans % 1000000007)

Submission status: Runtime Error

Solution code:
import sys
import functools
import operator
readline = sys.stdin.readline

N = int(input())

P = [-1 for _ in range(N + 1)]
C = [[] for _ in range(N + 1)]
for i, p in enumerate(readline().split()):
    P[i + 1] = int(p)
    C[int(p)].append(i + 1)

D = [[] for _ in range(N + 1)]


def add(depth, arr):
    D[depth] += arr
    for i in arr:
        if len(C[i]) > 0:
            add(depth + 1, C[i])

add(0, [0])

ans = 0
for depth in range(N + 1):
    if len(D[depth]) == 0:
        break
    dp = [[0 for i in range(2)] for j in range(N + 1)]
    num = [0 for i in range(N + 1)]
    for d in range(depth, -1, -1):
        for i in D[d]:
            if d == depth:
                dp[i][1] = 1
                dp[i][0] = 1
                num[i] = 1
            elif len(C[i]) == 0:
                dp[i][1] = 0
                dp[i][0] = 1
                num[i] = 0
            else:
                dp[i][1] = 0
                base = 1
                for j in C[i]:
                    base *= dp[j][0]
                for j in C[i]:
                    dp[i][1] += base * dp[j][1] // dp[j][0]
                    num[i] += num[j]
                dp[i][0] = 2 ** num[i] - dp[i][1]
    ans += (dp[0][1] * (2 ** (N + 1 - len(D[depth])))) % 1000000007

print(ans % 1000000007)