wym1111

Untitled

Sep 11th, 2023
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.14 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. #define ll long long
  5.  
  6. const int maxn = 1e5 + 10;
  7.  
  8. int n, k;
  9. int b[maxn];
  10. int dep[maxn], f[maxn];
  11. bool tag;
  12.  
  13.  
  14. void solve() {
  15.     cin >> n >> k;
  16.     for (int i = 1; i <= n; i ++) {
  17.         dep[i] = 0;
  18.         f[i] = i;
  19.     }
  20.     for (int i = 1; i <= n; i ++) {
  21.         cin >> b[i];
  22.     }
  23.     if (k == 1) {
  24.         for (int i = 1; i <= n; i ++) {
  25.             if (b[i] != i) {
  26.                 cout << "NO\n";
  27.                 return;
  28.             }
  29.         }
  30.         cout << "YES\n";
  31.         return;
  32.     }
  33.     if (k == 2) {
  34.         for (int i = 1; i <= n; i ++) {
  35.             if (b[b[i]] != i) {
  36.                 cout << "NO\n";
  37.                 return;
  38.             }
  39.         }
  40.         cout << "YES\n";
  41.     }
  42.     tag = 0;
  43.     for (int i = 1; i <= n; i ++) {
  44.         if (dep[i]) continue;
  45.         dep[i] = 1;
  46.         int x = i;
  47.         f[x] = i;
  48.         while (!dep[b[x]]) {
  49.             dep[b[x]] = dep[x] + 1;
  50.             x = b[x];
  51.             f[x] = i;
  52.         }
  53.         int res = dep[x] - dep[b[x]] + 1;
  54. //      cout << i << " " << res << endl;
  55.         if (f[x] != f[b[x]]) continue;
  56.         if (res == k) {
  57.             tag = 1;
  58.             break;
  59.         }
  60.     }
  61.     if (tag) cout << "YES\n";
  62.     else cout << "NO\n";
  63. }
  64. int main() {
  65.     ios::sync_with_stdio(false);
  66.     cin.tie(nullptr);
  67.     int T = 1;
  68.     cin >> T;
  69.     while (T--) {
  70.         solve();
  71.     }
  72.     return 0;
  73. }
Add Comment
Please, Sign In to add comment