atcoder#NOMURA2020D. Urban Planning

Urban Planning

Score : 700700 points

Problem Statement

There are NN towns numbered 1,2,,N1, 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 P1,P2,,PNP_1, P_2, \cdots, P_N. If Pi=1P_i = -1, it means that Town ii has not chosen the request; if 1PiN1 \leq P_i \leq N, it means that Town ii has chosen Town PiP_i.

Let KK be the number of towns ii such that Pi=1P_i = -1. There are (N1)K(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 (N1)K(N-1)^K numbers, modulo (109+710^9+7).

Constraints

  • 2N50002 \leq N \leq 5000
  • Pi=1P_i = -1 or 1PiN1 \leq P_i \leq N.
  • PiiP_i \neq i
  • All values in input are integers.

Input

Input is given from Standard Input in the following format:

NN

P1P_1 P2P_2 \cdots PNP_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 (N1)K(N-1)^K numbers, modulo (109+710^9+7).

4
2 1 -1 3
8

There are three ways to make requests, as follows:

  • Choose P1=2,P2=1,P3=1,P4=3P_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)(1,2),(1,3),(3,4) - are needed to meet the requests.
  • Choose P1=2,P2=1,P3=2,P4=3P_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)(1,2),(1,3),(3,4) - are needed to meet the requests.
  • Choose P1=2,P2=1,P3=4,P4=3P_1 = 2, P_2 = 1, P_3 = 4, P_4 = 3. In this case, at least two roads - for example, (1,2),(3,4)(1,2),(3,4) - are needed to meet the requests.

Note that it is not mandatory to connect Town ii and Town PiP_i directly.

The sum of the above numbers is 88.

2
2 1
1

There may be just one fixed way to make requests.

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