Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- #define s second
- #define f first
- #define ll long long
- #define pb push_back
- const ll M = 1e9 + 7;
- const int N = 1e6 + 2;
- int n, a[N], used[N], g;
- ll rou[N], k, ans = 1;
- void dfs(int v){
- used[v] = 1;
- if (used[a[v]] == 1){
- while (used[v] != 3){
- used[v] = 3;
- g++;
- v = a[v];
- }
- return;
- }
- if (used[a[v]] == 0){
- dfs(a[v]);
- }
- if (used[v] != 3)
- used[v] = 2;
- }
- int main(){
- cin >> n >> k;
- for (int i = 1; i <= n; i++){
- cin >> a[i];
- }
- rou[1] = k;
- rou[2] = (k * (k - 1));
- for (int i = 3; i <= n; i++){
- rou[i] = rou[i - 1] * (k - 1);
- rou[i] = (rou[i] + M) % M;
- }
- for (int i = 3; i <= n; i++){
- rou[i] -= rou[i - 1];
- rou[i] = (rou[i] + M) % M;
- }
- for (int i = 1; i <= n; i++){
- if (!used[i]){
- g = 0;
- dfs(i);
- if (g == 0){
- continue;
- }
- ans *= rou[g];
- ans = (ans + M) % M;
- }
- }
- for (int i = 1; i <= n; i++){
- if (used[i] == 2){
- g = i;
- while (used[g] != 3){
- ans *= (k - 1);
- ans = (ans + M) % M;
- used[g] = 3;
- g = a[g];
- }
- }
- }
- cout << (ans + M) % M;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement