Advertisement
Guest User

Untitled

a guest
Apr 22nd, 2019
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.44 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. #define s second
  6. #define f first
  7. #define ll long long
  8. #define pb push_back
  9.  
  10. const ll M = 1e9 + 7;
  11. const int N = 1e6 + 2;
  12.  
  13. int n, a[N], used[N], g;
  14.  
  15. ll rou[N], k, ans = 1;
  16.  
  17.  
  18. void dfs(int v){
  19. used[v] = 1;
  20. if (used[a[v]] == 1){
  21. while (used[v] != 3){
  22. used[v] = 3;
  23. g++;
  24. v = a[v];
  25. }
  26. return;
  27. }
  28. if (used[a[v]] == 0){
  29. dfs(a[v]);
  30. }
  31. if (used[v] != 3)
  32. used[v] = 2;
  33. }
  34.  
  35. int main(){
  36. cin >> n >> k;
  37. for (int i = 1; i <= n; i++){
  38. cin >> a[i];
  39. }
  40. rou[1] = k;
  41. rou[2] = (k * (k - 1));
  42. for (int i = 3; i <= n; i++){
  43. rou[i] = rou[i - 1] * (k - 1);
  44. rou[i] = (rou[i] + M) % M;
  45. }
  46. for (int i = 3; i <= n; i++){
  47. rou[i] -= rou[i - 1];
  48. rou[i] = (rou[i] + M) % M;
  49. }
  50.  
  51. for (int i = 1; i <= n; i++){
  52. if (!used[i]){
  53. g = 0;
  54. dfs(i);
  55. if (g == 0){
  56. continue;
  57. }
  58. ans *= rou[g];
  59. ans = (ans + M) % M;
  60. }
  61. }
  62. for (int i = 1; i <= n; i++){
  63. if (used[i] == 2){
  64. g = i;
  65. while (used[g] != 3){
  66. ans *= (k - 1);
  67. ans = (ans + M) % M;
  68. used[g] = 3;
  69. g = a[g];
  70. }
  71. }
  72. }
  73. cout << (ans + M) % M;
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement