This page is still under construction.

Parts of this page are still being built. What you see may change.

Coloring Book

Time limit1sMemory limit128 MB

Summary
Count the assignments of K colors to N pictures so each picture i differs from picture f_i unless f_i equals i, modulo 1,000,000,007.
Level

Medium6 of 10

Topics
Graph, Combinatorics, Math
Solved
No attempts yet

Problem

Sanggeun colors pictures whenever he has spare time. He has a palette holding KK colors and one brush. His friend Seonyeong gave him a coloring book for his birthday. The book has NN pictures, numbered 1 through NN.

Sanggeun wants to paint every picture with one of the KK colors. Seonyeong likes flashy results, so she fixed NN numbers f1,f2,…,fNf_1, f_2, \dots, f_N. Picture ii must be painted a different color from picture fif_i. When ii and fif_i are the same, picture ii can be painted with no restriction.

Given NN, KK, and every fif_i, write a program that counts the ways Sanggeun can color the book.

Input

The first line contains NN and KK. (1≤N,K≤1,000,0001 \le N, K \le 1{,}000{,}000)

The second line contains the NN numbers f1,f2,…,fNf_1, f_2, \dots, f_N. (1≤fi≤N1 \le f_i \le N)

Output

Print the number of ways to color the coloring book on the first line. The count gets very large, so print it modulo 1,000,000,0071{,}000{,}000{,}007.

Hint

When N=2N = 2, K=3K = 3, and f=(2,1)f = (2, 1), pictures 1 and 2 cannot take the same color. Writing the two colors as an ordered pair, the six possibilities are (1,2), (1,3), (2,1), (2,3), (3,1), (3,2).

Examples4

  1. Example 1

    Input
    2 3
    2 1
    
    Expected output
    6
    
  2. Example 2

    Input
    3 4
    2 3 1
    
    Expected output
    24
    
  3. Example 3

    Input
    3 4
    2 1 1
    
    Expected output
    36
    
  4. Example 4

    Input
    3 4
    1 1 2
    
    Expected output
    36