Advertisement
RaFiN_

Infinite Path cf-1327D

Jul 1st, 2020
859
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.53 KB | None | 0 0
  1.  
  2. //cyclic permutation
  3. //tutorial - https://www.youtube.com/watch?v=rwAqAmljjxU
  4. #include <bits/stdc++.h>
  5. using namespace std;
  6.  
  7. const int N = 1e6 + 100;
  8.  
  9. vector<int> all_col;
  10. int p[N], c[N];
  11. int vis[N];
  12.  
  13. void dfs(int u, int d) {
  14.     all_col.push_back(c[u]);
  15.     vis[u] = 1;
  16.     if(vis[p[u]] == 0) dfs(p[u], d+1);
  17. }
  18.  
  19.  
  20. int main() {
  21.     // freopen("in.txt", "r", stdin);
  22.     ios::sync_with_stdio(0);
  23.     cin.tie(0);
  24.  
  25.     int tc;
  26.     cin >> tc;
  27.     while(tc--) {
  28.         int n;
  29.         cin >> n;
  30.         for(int i = 1; i <= n; i++) cin >> p[i];
  31.         for(int i = 1; i <= n; i++) cin >> c[i];
  32.         for(int i = 1; i <= n; i++) vis[i] = 0;
  33.         int ans = 1e9;
  34.         for(int i = 1; i <= n; i++) {
  35.             if(vis[i] == 0) {
  36.                 dfs(i, 0);
  37.                 int cyc_len = (int)all_col.size();
  38.                 ans = min(ans, cyc_len);
  39.                 for(int k = 1; k <= cyc_len; k++) {
  40.                     if(cyc_len%k != 0) continue;
  41.                     for(int i = 0; i < k; i++) {
  42.                         bool found = true;
  43.                         for(int j = i; j < cyc_len; j += k) {
  44.                             if(all_col[i] != all_col[j]) {
  45.                                 found = false;
  46.                                 break;
  47.                             }
  48.                         }
  49.                         if(found) ans = min(ans, k);
  50.                     }
  51.                 }
  52.                 all_col.clear();
  53.             }
  54.         }
  55.         cout << ans << endl;
  56.     }
  57.  
  58.     return 0;
  59. }
  60.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement