#P7752. [COCI 2013/2014 #2] PALETA

[COCI 2013/2014 #2] PALETA

Description

Mirko has kk colors and nn pictures that need to be colored. The pictures are numbered from 11 to nn, and he decided to fill each picture using one of the kk colors.

To do this, he chose nn numbers fif_i, and decided to color the pictures in the following way:

  • If fiif_i\ne i, then the color of picture ii must not be the same as the color of picture fif_i.
  • If fi=if_i=i, then as long as all other conditions are satisfied, he may color picture fif_i with any color.

You need to find the number of possible ways to color the pictures.

Since the output may be very large, you only need to output the answer modulo 109+7\bm{10^9+7}.

Input Format

The first line contains two integers n,kn, k, representing the number of pictures and the number of colors.

The next nn lines each contain fif_i.

Output Format

Output a single integer: the number of possible ways to color the pictures modulo 109+710^9+7.

2 3
2 1
6
3 4
2 3 1
24
3 4
2 1 1
36
3 4
1 1 2
36

Hint

Explanation for Sample 1

There are 33 colors, and the color of picture 22 must not be the same as the color of picture 11. The possible colorings are (1,2),(1,3),(2,1),(2,3),(3,1),(3,2)(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2), where the two numbers in parentheses represent the colors of the two pictures.

Explanation for Sample 4

There are 44 colors.

  • For picture 11, it can be colored with any color.
  • For picture 22, its color must not be the same as the color of picture 11.
  • For picture 33, its color must not be the same as the color of picture 22.

That is, picture 22 can be colored in 33 ways excluding the color of picture 11, and picture 33 can be colored in 33 ways excluding the color of picture 22.

The answer is 4×3×3=364\times 3\times 3=36.

Constraints

  • For 50%50\% of the testdata, fifj(1ijn)f_i\ne f_j(1\le i\ne j\le n).
  • For 100%100\% of the testdata, 1n,k1061\le n,k\le 10^6.

For all valid fif_i, 1fin1\le f_i\le n.

Source

This problem is translated from COCI2013-2014 CONTEST 2 T5 PALETA.

According to the original testdata settings, the full score of this problem is 140140 points.

Translated by ChatGPT 5