Problem:


Score : 700 points

Problem Statement

There are N towns numbered 1, 2, \cdots, N.

Some roads are planned to be built so that each of them connects two distinct towns bidirectionally. Currently, there are no roads connecting towns.

In the planning of construction, each town chooses one town different from itself and requests the following: roads are built so that the chosen town is reachable from itself using one or more roads.

These requests from the towns are represented by an array P_1, P_2, \cdots, P_N. If P_i = -1, it means that Town i has not chosen the request; if 1 \leq P_i \leq N, it means that Town i has chosen Town P_i.

Let K be the number of towns i such that P_i = -1. There are (N-1)^K ways in which the towns can make the requests. For each way to make requests, find the minimum number of roads needed to meet all the requests, and print the sum of those (N-1)^K numbers, modulo (10^9+7).

Constraints

2 \leq N \leq 5000

P_i = -1 or 1 \leq P_i \leq N.

P_i \neq i

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
P_1 P_2 \cdots P_N

Output

For each way to make requests, find the minimum number of roads needed to meet all the requests, and print the sum of those (N-1)^K numbers, modulo (10^9+7).

Sample Input 1

4
2 1 -1 3

Sample Output 1

8

There are three ways to make requests, as follows:

Choose P_1 = 2, P_2 = 1, P_3 = 1, P_4 = 3. In this case, at least three roads - for example, (1,2),(1,3),(3,4) - are needed to meet the requests.

Choose P_1 = 2, P_2 = 1, P_3 = 2, P_4 = 3. In this case, at least three roads - for example, (1,2),(1,3),(3,4) - are needed to meet the requests.

Choose P_1 = 2, P_2 = 1, P_3 = 4, P_4 = 3. In this case, at least two roads - for example, (1,2),(3,4) - are needed to meet the requests.

Note that it is not mandatory to connect Town i and Town P_i directly.

The sum of the above numbers is 8.

Sample Input 2

2
2 1

Sample Output 2

1

There may be just one fixed way to make requests.

Sample Input 3

10
2 6 9 -1 6 9 -1 -1 -1 -1

Sample Output 3

527841



Sample input:
4
2 1 -1 3


Sample output:
8

Submission status: Wrong Answer

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, cos, radians, pi, sin
from operator import mul
from functools import reduce
from operator import mul

mod = 10 ** 9 + 7
sys.setrecursionlimit(2147483647)
INF = 10 ** 13
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def I(): return int(sys.stdin.buffer.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)]


class UnionFind:
    def __init__(self, n):
        # 負  : 根であることを示す。絶対値はランクを示す
        # 非負: 根でないことを示す。値は親を示す
        self.table = [-1] * n
        self.size = [1] * n
        self.group_num = n

    def root(self, x):
        if self.table[x] < 0:
            return x
        else:
            self.table[x] = self.root(self.table[x])
            return self.table[x]

    def get_size(self, x):
        r = self.root(x)
        return self.size[r]

    def is_same(self, x, y):
        return self.root(x) == self.root(y)

    def union(self, x, y):
        r1 = self.root(x)
        r2 = self.root(y)
        if r1 == r2:
            return
        # ランクの取得
        d1 = self.table[r1]
        d2 = self.table[r2]
        if d1 <= d2:
            self.table[r2] = r1
            self.size[r1] += self.size[r2]
            if d1 == d2:
                self.table[r1] -= 1
        else:
            self.table[r1] = r2
            self.size[r2] += self.size[r1]
        self.group_num -= 1

n = I()
P = LI()

fac = [1] * (n + 1)
inv = [1] * (n + 1)
for j in range(1, n + 1):
    fac[j] = fac[j-1] * j % mod


inv[n] = pow(fac[n], mod-2, mod)
for j in range(n-1, -1, -1):
    inv[j] = inv[j+1] * (j+1) % mod


def comb(n, r):
    if r > n or n < 0 or r < 0:
        return 0
    return fac[n] * inv[n - r] * inv[r] % mod


ret = 0
for p in P:
    if p == -1:
        ret += 1

U = UnionFind(n)
for i in range(n):
    if P[i] != -1:
        U.union(P[i] - 1, i)



L = []
for j in range(n):
    if P[j] == -1:
        L += [U.size[j]]

dp = [0] * (len(L) + 1)
dp[0] = 1
for l in range(1, len(L) + 1):
    for m in range(l, -1, -1):
        dp[m] += dp[m - 1] * L[l - 1]

if L:
    dp[1] = sum(L) - len(L)
cycle_cnt = 0
for i in range(1, len(L) + 1):
    cycle_cnt += fac[i - 1] * dp[i] * pow(n - 1, len(L) - i, mod)

ans = (n - (U.group_num - ret)) * pow(n - 1, ret, mod)
print((ans - cycle_cnt) % mod)

Submission status: Wrong Answer

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, cos, radians, pi, sin
from operator import mul
from functools import reduce
from operator import mul

mod = 10 ** 9 + 7
sys.setrecursionlimit(2147483647)
INF = 10 ** 13
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def I(): return int(sys.stdin.buffer.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)]


class UnionFind:
    def __init__(self, n):
        # 負  : 根であることを示す。絶対値はランクを示す
        # 非負: 根でないことを示す。値は親を示す
        self.table = [-1] * n
        self.size = [1] * n
        self.group_num = n

    def root(self, x):
        if self.table[x] < 0:
            return x
        else:
            self.table[x] = self.root(self.table[x])
            return self.table[x]

    def get_size(self, x):
        r = self.root(x)
        return self.size[r]

    def is_same(self, x, y):
        return self.root(x) == self.root(y)

    def union(self, x, y):
        r1 = self.root(x)
        r2 = self.root(y)
        if r1 == r2:
            return
        # ランクの取得
        d1 = self.table[r1]
        d2 = self.table[r2]
        if d1 <= d2:
            self.table[r2] = r1
            self.size[r1] += self.size[r2]
            if d1 == d2:
                self.table[r1] -= 1
        else:
            self.table[r1] = r2
            self.size[r2] += self.size[r1]
        self.group_num -= 1

n = I()
P = LI()

fac = [1] * (n + 1)
inv = [1] * (n + 1)
for j in range(1, n + 1):
    fac[j] = fac[j-1] * j % mod


inv[n] = pow(fac[n], mod-2, mod)
for j in range(n-1, -1, -1):
    inv[j] = inv[j+1] * (j+1) % mod


def comb(n, r):
    if r > n or n < 0 or r < 0:
        return 0
    return fac[n] * inv[n - r] * inv[r] % mod


ret = 0
for p in P:
    if p == -1:
        ret += 1

U = UnionFind(n)
for i in range(n):
    if P[i] != -1:
        U.union(P[i] - 1, i)



L = []
for j in range(n):
    if P[j] == -1:
        L += [U.size[j]]

dp = [0] * (len(L) + 1)
dp[0] = 1
for l in range(1, len(L) + 1):
    for m in range(l, -1, -1):
        dp[m] = dp[m - 1] * l

if L:
    dp[1] = sum(L) - len(L)
cycle_cnt = 0
for i in range(1, len(L) + 1):
    cycle_cnt += fac[i - 1] * dp[i]

ans = (n - (U.group_num - ret)) * pow(n - 1, ret, mod)
print((ans - cycle_cnt) % mod)

Submission status: Wrong Answer

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, cos, radians, pi, sin
from operator import mul
from functools import reduce
from operator import mul

mod = 10 ** 9 + 7
sys.setrecursionlimit(2147483647)
INF = 10 ** 13
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def I(): return int(sys.stdin.buffer.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)]


class UnionFind:
    def __init__(self, n):
        # 負  : 根であることを示す。絶対値はランクを示す
        # 非負: 根でないことを示す。値は親を示す
        self.table = [-1] * n
        self.size = [1] * n
        self.group_num = n

    def root(self, x):
        if self.table[x] < 0:
            return x
        else:
            self.table[x] = self.root(self.table[x])
            return self.table[x]

    def get_size(self, x):
        r = self.root(x)
        return self.size[r]

    def is_same(self, x, y):
        return self.root(x) == self.root(y)

    def union(self, x, y):
        r1 = self.root(x)
        r2 = self.root(y)
        if r1 == r2:
            return
        # ランクの取得
        d1 = self.table[r1]
        d2 = self.table[r2]
        if d1 <= d2:
            self.table[r2] = r1
            self.size[r1] += self.size[r2]
            if d1 == d2:
                self.table[r1] -= 1
        else:
            self.table[r1] = r2
            self.size[r2] += self.size[r1]
        self.group_num -= 1

n = I()
P = LI()

fac = [1] * (n + 1)
inv = [1] * (n + 1)
for j in range(1, n + 1):
    fac[j] = fac[j-1] * j % mod


inv[n] = pow(fac[n], mod-2, mod)
for j in range(n-1, -1, -1):
    inv[j] = inv[j+1] * (j+1) % mod


def comb(n, r):
    if r > n or n < 0 or r < 0:
        return 0
    return fac[n] * inv[n - r] * inv[r] % mod


ret = 0
for p in P:
    if p == -1:
        ret += 1

U = UnionFind(n)
for i in range(n):
    if P[i] != -1:
        U.union(P[i] - 1, i)

ans = (n - U.group_num + ret) * pow(n - 1, ret, mod)

L = []
for j in range(n):
    if P[j] == -1:
        L += [U.size[j]]

dp = [0] * (len(L) + 1)
dp[0] = 1
for l in range(1, len(L) + 1):
    for m in range(l, -1, -1):
        dp[m] = dp[m - 1] * l

if L:
    dp[1] = sum(L) - len(L)
cycle_cnt = 0
for i in range(1, len(L) + 1):
    cycle_cnt += fac[i - 1] * dp[i]

print((ans - cycle_cnt) % mod)

Submission status: Wrong Answer

Solution code:
N=int(input())
A=list(map(int,input().split()))

MOD = 10**9 + 7
yet=[]
belongto=[-1]*N
group=[]
groupsize=[]

for i in range(N):
    if A[i]>0:
        nex=A[i]-1
        if belongto[nex]<0 and belongto[i]<0:
            belongto[nex]=len(group)
            belongto[i]=len(group)
            group.append([i+1,A[i]])
        elif belongto[nex]>=0 and belongto[i]<0:
            belongto[i]=belongto[nex]
            group[belongto[A[i]-1]].append(i+1)
        elif belongto[nex]<0 and belongto[i]>=0:
            belongto[nex]=belongto[i]
            group[belongto[i]].append(A[i])
        elif belongto[nex]==belongto[i]:
            continue
        elif belongto[nex]>=0 and belongto[i]>=0:
            ori_group=belongto[nex]
            for j in group[belongto[nex]]:
                belongto[j-1]=belongto[i]
            group[belongto[i]]+=group[ori_group]
            group[ori_group]=[]
    elif A[i]<0:
        yet.append(i+1)
        if belongto[i]==-1:
            belongto[i]=len(group)
            group.append([i+1])
for i in range(len(group)):
    groupsize.append(len(group[i]))

    
if len(yet)>0:
    comb=[[0]*len(yet) for _ in range(len(yet))]
    comb[0][0]=groupsize[belongto[yet[0]-1]]-1

    for i in range(len(yet)-1):
        comb[i+1][0]=(comb[i][0]+groupsize[belongto[yet[i+1]-1]]-1)
        comb[i+1][1]=((comb[i][0]+i+1)*groupsize[belongto[yet[i+1]-1]])%MOD
        for j in range(1,i+1):
            comb[i+1][j]=(comb[i][j]+comb[i+1][j])
            comb[i+1][j+1]=(comb[i][j]*groupsize[belongto[yet[i+1]-1]]*(j+1))%MOD

groupnum =0
for agroup in group:
    if len(agroup)>0:
        groupnum+=1
del group
del belongto
del A
total=(N-(groupnum-len(yet)))%MOD
if len(yet)==0:
    print(total)
else:
    for i in range(len(yet)):
        total = (total*(N-1))%MOD
        total=(total-comb[len(yet)-1][i])

    print(total)

Submission status: Wrong Answer

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



class UnionFindTree:
    def __init__(self, n):
        self.n = n
        self.parent = list(range(n))
        self.size = [1] * n

    def root(self, i):
        inter = set()
        while self.parent[i]!=i:
            inter.add(i)
            i = self.parent[i]
        r = i
        for i in inter:
            self.parent[i] = r
        return r

    def connect(self, i, j):
        if i==j:
            return
        ri = self.root(i)
        rj = self.root(j)
        if ri==rj:
            return
        if self.size[ri]<self.size[rj]:
            self.parent[ri] = rj
            self.size[rj] += self.size[ri]
        else:
            self.parent[rj] = ri
            self.size[ri] += self.size[rj]


n = int(input())
uf = UnionFindTree(n)
ps = list(map(int, input().split()))
k = 0
for i,p in enumerate(ps):
    if p<0:
        k += 1
        continue
    uf.connect(i,p-1)
for i in range(n):
    uf.root(i)
from collections import Counter, defaultdict
M = 10**9+7
ncount = Counter(uf.parent)
mcount = defaultdict(int)
for i,g in enumerate(uf.parent):
    if ps[i]==-1:
        mcount[g] += 1

ans = sum(v-1 for v in ncount.values())
ans *= pow(n-1, k, M)

for kk in ncount.keys():
    ncount[kk] -= mcount[kk]

for kk,mm in mcount.items():
    if mm==0:
        continue
    nn = ncount[kk]
    ans += (n - mm - nn)*pow(n-1, k-1, M)*mm
    ans %= M

nums = [nn+mcount[k] for k,nn in ncount.items() if mcount[k]]
l = len(nums)
dp = [[0] * l for _ in range(l)]
# dp[i][j] : i番目まで使うときの周期j+1の個数
if nums:
    dp[0][0] = nums[0]
    for i in range(1,l):
        dp[i][0] = dp[i-1][0] + nums[i]

    for i in range(1,l):
        for j in range(1,l):
            dp[i][j] += dp[i-1][j-1] * nums[i] * j + dp[i-1][j]
            dp[i][j] %= M

    for j in range(1, l):
        ans -= dp[-1][j]*pow(n-1, l-j-1, M)

print(ans)

Submission status: Wrong Answer

Solution code:
N=int(input())
A=list(map(int,input().split()))

MOD = 10**9 + 7
yet=[]
belongto=[-1]*N
group=[]
groupsize=[]

for i in range(N):
    if A[i]>0:
        nex=A[i]-1
        if belongto[nex]<0 and belongto[i]<0:
            belongto[nex]=len(group)
            belongto[i]=len(group)
            group.append([i+1,A[i]])
        elif belongto[nex]>=0 and belongto[i]<0:
            belongto[i]=belongto[nex]
            group[belongto[A[i]-1]].append(i+1)
        elif belongto[nex]<0 and belongto[i]>=0:
            belongto[nex]=belongto[i]
            group[belongto[i]].append(A[i])
        elif belongto[nex]==belongto[i]:
            continue
        elif belongto[nex]>=0 and belongto[i]>=0:
            ori_group=belongto[nex]
            for j in group[belongto[nex]]:
                belongto[j-1]=belongto[i]
            group[belongto[i]]+=group[ori_group]
            group[ori_group]=[]
    elif A[i]<0:
        yet.append(i+1)
        if belongto[i]==-1:
            belongto[i]=len(group)
            group.append([i+1])
for i in range(len(group)):
    groupsize.append(len(group[i]))

    
if len(yet)>0:
    comb=[[0]*len(yet) for _ in range(len(yet))]
    comb[0][0]=groupsize[belongto[yet[0]-1]]-1

    for i in range(len(yet)-1):
        comb[i+1][0]=(comb[i][0]+groupsize[belongto[yet[i+1]-1]]-1)
        comb[i+1][1]=((comb[i][0]+i+1)*groupsize[belongto[yet[i+1]-1]])%MOD
        for j in range(1,i+1):
            comb[i+1][j]=(comb[i][j]+comb[i+1][j])
            comb[i+1][j+1]=(comb[i][j]*groupsize[belongto[yet[i+1]-1]]*(j+1))%MOD

groupnum =0
for agroup in group:
    if len(agroup)>0:
        groupnum+=1

total=(N-(groupnum-len(yet)))%MOD
if len(yet)==0:
    print(total)
else:
    for i in range(len(yet)):
        total = (total*(N-1))%MOD
        total=(total-comb[len(yet)-1][i])

    print(total)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys
from functools import lru_cache
sys.setrecursionlimit(10**8)
INF = float("inf")

MOD = 1000000007  # type: int


@lru_cache(maxsize=None)
def factorial(n):
    if n == 0:
        return 1
    else:
        return n*factorial(n-1)


class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

    def size(self, x):
        return -self.parents[self.find(x)]

    def same(self, x, y):
        return self.find(x) == self.find(y)

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):
        return len(self.roots())

    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())


def main():
    N = int(input())
    P = list(map(int, input().split()))

    # 確定している道でグルーピングすることは問題ない
    uf = UnionFind(N)

    K = 0
    undef = []
    for i, p in enumerate(P):
        if p != -1:
            uf.union(i, p-1)
        else:
            K += 1
            undef.append(i)

    groups = {}
    mapping = {}
    for i, r in enumerate(uf.roots()):
        groups[r] = [uf.size(r), True]
        mapping[i] = r
    for u in undef:
        groups[uf.find(u)][1] = False

    # 作り直し（むだっぽい）
    sizes = []
    looped = []
    for k, v in groups.items():
        sizes.append(v[0])
        looped.append(v[1])
    # print(sizes)
    # print(looped)

    # dp[i, j]: i個の根付き木を見てj個を選んだ時の\sum{\prod_v S_v}
    dp = [0]*(K+1)
    dp[0] = 1
    dp_new = dp[:]
    for i in range(1, K+1):
        for j in range(i):
            dp_new[j+1] += dp[j]*sizes[i-1]
        dp = dp_new[:]
        # print(dp)

    # ただしj=1個を選んだ時のものは正しくない。
    # この時は特別にsize[i]-1を考える必要がある
    if len(dp) >= 2:
        tot = 0
        for s, l in zip(sizes, looped):
            if l == False:
                tot += s-1
        dp[1] = tot
        # print(dp)

    cycle_count = 0
    for i in range(1, K+1):
        # i個のグループからなるサイクルがひとつできる
        buf = dp[i]
        buf *= factorial(i-1)
        buf %= MOD
        buf *= pow(N-1, K-i, MOD)
        buf %= MOD
        cycle_count += buf
        # print("数え上げ", dp[i], factorial(i-1), pow(N-1, K-i, MOD))
    # print(f"cycle_count, {cycle_count}")

    # すでに固定サイクルがあれば数える
    cycle_count += (len(groups)-K)*pow(N-1, K, MOD)
    # print("!", (len(groups)-K)*pow(N-1, K, MOD))
    # for s, l in zip(sizes, looped):
    #     if l == True:
    #         cycle_count += pow(N-1, K, MOD)
    #         print("固定サイクルカウント", 1, pow(N-1, K, MOD))
    # print("固定サイクル", cycle_count)
    # 62649

    # \sigma_{つなぎ方} N
    ans = N*pow(N-1, K, MOD)
    # print("sigma_{つなぎ方} N", ans)
    ans %= MOD
    ans = ans - cycle_count
    ans %= MOD

    print(ans)

    return


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
def main():
  N = int(input())
  P = list(map(int,input().split()))
  from collections import deque
  P = [i-1 for i in P]
  road = [[] for _ in range(N)]
  MOD = 10**9 + 7

  plu = 0
  for i in range(N):
    if P[i]>=0:
      plu += 1
      road[P[i]].append(i)
      road[i].append(P[i])


  mi = N - plu
  num_pattern = pow(N - 1, mi, MOD)
  ans = N * num_pattern
  ans %= MOD

  flag = [False] * N
  num_group = 0
  group_list = [-1] * N
  for i in range(N):
    if flag[i]:
      continue

    if len(road[i])==0:
      group_list[i] = num_group
      num_group += 1
      flag[i] = True

    else:
      q = deque(road[i])
      if flag[i]:
        continue

      flag[i] = True
      group_list[i] = num_group
      while len(q)!=0:
        x = q.popleft()
        if flag[x]:
          continue
        else:
          flag[x] = True
          group_list[x] = num_group
          q = q + deque(road[x])

      num_group += 1

  group_member = [0] * num_group
  for i in group_list:
    group_member[i] += 1

  mi_group = [0] * mi
  mi_num = 0
  for i in range(N):
    if P[i]>=0:
      continue
    else:
      mi_group[mi_num] = group_member[group_list[i]]
      mi_num += 1

  plu_num = num_group - mi_num
  dp = [[0] * (mi_num+1) for _ in range(mi_num+1)]
  
main()

Submission status: Wrong Answer

Solution code:
def main():
  N = int(input())
  P = list(map(int,input().split()))
  from collections import deque
  P = [i-1 for i in P]
  road = [[] for _ in range(N)]
  MOD = 10**9 + 7

  plu = 0
  for i in range(N):
    if P[i]>=0:
      plu += 1
      road[P[i]].append(i)
      road[i].append(P[i])


  mi = N - plu
  num_pattern = pow(N - 1, mi, MOD)
  ans = N * num_pattern
  ans %= MOD

  flag = [False] * N
  num_group = 0
  group_list = [-1] * N
  for i in range(N):
    if flag[i]:
      continue

    if len(road[i])==0:
      group_list[i] = num_group
      num_group += 1
      flag[i] = True

    else:
      q = deque(road[i])
      if flag[i]:
        continue

      flag[i] = True
      group_list[i] = num_group
      while len(q)!=0:
        x = q.popleft()
        if flag[x]:
          continue
        else:
          flag[x] = True
          group_list[x] = num_group
          q = q + deque(road[x])

      num_group += 1

  group_member = [0] * num_group
  for i in group_list:
    group_member[i] += 1

  mi_group = [0] * mi
  mi_num = 0
  for i in range(N):
    if P[i]>=0:
      continue
    else:
      mi_group[mi_num] = group_member[group_list[i]]
      mi_num += 1

  plu_num = num_group - mi_num
  dp = [[0] * (mi_num+1) for _ in range(mi_num+1)]
  for i in range(mi_num):
    for j in range(i+1):
      dp[i+1][j] += dp[i][j]
      if j>1:
        dp[i+1][j+1] += dp[i][j] * mi_group[i]
      elif j==1:
        dp[i+1][j+1] += (dp[i][j]+i) * mi_group[i]
      else:
        dp[i+1][j+1] += mi_group[i] - 1

  
main()

Submission status: Wrong Answer

Solution code:
def main():
  N = int(input())
  P = list(map(int,input().split()))
  from collections import deque
  P = [i-1 for i in P]
  road = [[] for _ in range(N)]
  MOD = 10**9 + 7

  plu = 0
  for i in range(N):
    if P[i]>=0:
      plu += 1
      road[P[i]].append(i)
      road[i].append(P[i])


  mi = N - plu
  num_pattern = pow(N - 1, mi, MOD)
  ans = N * num_pattern
  ans %= MOD

  flag = [False] * N
  num_group = 0
  group_list = [-1] * N
  for i in range(N):
    if flag[i]:
      continue

    if len(road[i])==0:
      group_list[i] = num_group
      num_group += 1
      flag[i] = True

    else:
      q = deque(road[i])
      if flag[i]:
        continue

      flag[i] = True
      group_list[i] = num_group
      while len(q)!=0:
        x = q.popleft()
        if flag[x]:
          continue
        else:
          flag[x] = True
          group_list[x] = num_group
          q = q + deque(road[x])

      num_group += 1

  group_member = [0] * num_group
  for i in group_list:
    group_member[i] += 1

  mi_group = [0] * mi
  mi_num = 0
  for i in range(N):
    if P[i]>=0:
      continue
    else:
      mi_group[mi_num] = group_member[group_list[i]]
      mi_num += 1

  plu_num = num_group - mi_num
  dp = [[0] * (mi_num+1) for _ in range(mi_num+1)]
  for i in range(mi_num):
    for j in range(i+1):
      dp[i+1][j] += dp[i][j]
      if j>1:
        dp[i+1][j+1] += dp[i][j] * mi_group[i]
      elif j==1:
        dp[i+1][j+1] += (dp[i][j]+i) * mi_group[i]
      else:
        dp[i+1][j+1] += mi_group[i] - 1

  l = dp[-1]
  factorial = 1
  power = [1]*(mi_num+1)
  factorial = [1]*(mi_num+1)
  for i in range(1,mi_num+1):
    power[i] = power[i-1] * (N-1)
    power[i] %= MOD
    factorial[i] = factorial[i-1]*i
    factorial[i] %= MOD


  for i in range(1,len(l)):
    ans -= l[i] * factorial[i-1] * power[mi_num-i]
    ans %= MOD

  ans -= plu_num * power[mi_num]
  print(ans)
  
main()

Submission status: Wrong Answer

Solution code:
N = int(input())
P = list(map(int,input().split()))
from collections import deque
P = [i-1 for i in P]
road = [[] for _ in range(N)]
MOD = 10**9 + 7

plu = 0
for i in range(N):
  if P[i]>=0:
    plu += 1
    road[P[i]].append(i)
    road[i].append(P[i])

    
mi = N - plu
num_pattern = pow(N - 1, mi, MOD)
ans = N * num_pattern
ans %= MOD

flag = [False] * N
num_group = 0
group_list = [-1] * N
for i in range(N):
  if flag[i]:
    continue

  if len(road[i])==0:
    group_list[i] = num_group
    num_group += 1
    flag[i] = True
    
  else:
    q = deque(road[i])
    if flag[i]:
      continue

    flag[i] = True
    group_list[i] = num_group
    while len(q)!=0:
      x = q.popleft()
      if flag[x]:
        continue
      else:
        flag[x] = True
        group_list[x] = num_group
        q = q + deque(road[x])
        
    num_group += 1
    
group_member = [0] * num_group
for i in group_list:
  group_member[i] += 1
  
mi_group = [0] * mi
mi_num = 0
for i in range(N):
  if P[i]>=0:
    continue
  else:
    mi_group[mi_num] = group_member[group_list[i]]
    mi_num += 1

plu_num = num_group - mi_num
dp = [[0] * (mi_num+1) for _ in range(mi_num+1)]
for i in range(mi_num):
  for j in range(i+1):
    dp[i+1][j] += dp[i][j]
    if j>1:
      dp[i+1][j+1] += dp[i][j] * mi_group[i]
    elif j==1:
      dp[i+1][j+1] += (dp[i][j]+i) * mi_group[i]
    else:
      dp[i+1][j+1] += mi_group[i] - 1

l = dp[-1]
factorial = 1
power = [1]*(mi_num+1)
factorial = [1]*(mi_num+1)
for i in range(1,mi_num+1):
  power[i] = power[i-1] * (N-1)
  power[i] %= MOD
  factorial[i] = factorial[i-1]*i
  factorial[i] %= MOD
  

for i in range(1,len(l)):
  ans -= l[i] * factorial[i-1] * power[mi_num-i]
  ans %= MOD
  
ans -= plu_num * power[mi_num]
print(ans)

Submission status: Wrong Answer

Solution code:
def productall(a):
    N = len(a)
    if N == 0: return [1]
    A = [1] * N + a[:]
    P = 10 ** 9 + 7
    k = 12
    K = k * 8
    pa1 = (1 << k * 4 + 16) - ((1 << k * 4 + 16) % P)
    pa2 = (1 << k * 2 + 24) - ((1 << k * 2 + 24) % P)
    pa3 = (1 << k + 28) - ((1 << k + 28) % P)
    def modP(x):
        x -= ((x & m1) >> k * 4 + 16) * pa1
        x -= ((x & m2) >> k * 2 + 24) * pa2
        x -= ((x & m3) >> k + 28) * pa3
        return x
    
    c = 2
    m1 = int(("1" * (k * 4 - 16) + "0" * (k * 4 + 16)) * c, 2)
    m2 = int(("1" * (k * 6 - 24) + "0" * (k * 2 + 24)) * c, 2)
    m3 = int(("1" * (k * 7 - 28) + "0" * (k + 28)) * c, 2)
    for i in range(1, N)[::-1]:
        if i == 1 << i.bit_length() - 1:
            c *= 2
            m1 = int(("1" * (k * 4 - 16) + "0" * (k * 4 + 16)) * c, 2)
            m2 = int(("1" * (k * 6 - 24) + "0" * (k * 2 + 24)) * c, 2)
            m3 = int(("1" * (k * 7 - 28) + "0" * (k + 28)) * c, 2)
        A[i] = modP(A[2*i] * A[2*i+1])

    t = bin(A[1])[2:] + "_"
    return [int(t[-(i+1) * K - 1:-i * K - 1], 2) % P for i in range((len(t)+K-2) // K)]
def par(a):
    L = []
    while P[a] != a:
        L.append(a)
        a = P[a]
    for l in L:
        P[l] = a
    return a
def unite(a, b):
    pa = par(a)
    pb = par(b)
    if pa == pb: return
    if LEN[pa] < LEN[pb]:
        a, b, pa, pb = b, a, pb, pa
    P[pb] = pa
    if LEN[pa] == LEN[pb]: LEN[pa] += 1
    CNT[pa] += CNT[pb]
def cnt(a):
    return CNT[par(a)]

N = int(input())
P = [i for i in range(N)]
LEN = [1] * N
CNT = [1] * N
FULL = [0] * N
A = [int(a) - 1 for a in input().split()]
for i, a in enumerate(A):
    if a < 0: continue
    if par(i) != par(a):
        unite(i, a)
    else:
        FULL[i] = 1
for i in range(N):
    if FULL[i]:
        FULL[par(i)] = 1
X = []
Y = []
for i in range(N):
    if par(i) == i:
        if FULL[i] == 0:
            X.append(CNT[i])
        else:
            Y.append(CNT[i])
M = len(X)
mod = 10 ** 9 + 7
ans = (sum(X) + sum(Y) - len(Y)) * pow(N - 1, M, mod) % mod
L = productall([(a << 96) + 1 for a in X])
fa = 1
if M: ans = (ans + M * pow(N - 1, M - 1, mod)) % mod
for i, l in enumerate(L):
    if i == 0: continue
    ans = (ans - l * fa * pow(N - 1, M - i + mod - 1, mod)) % mod
    fa = fa * i % mod
print(ans)