Beingamanforever

Permutation Graph, Minimum Cyclic shift

Jan 22nd, 2025
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.99 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. // #include <atcoder/all>
  3. using namespace std;
  4. #define int long long
  5. #define all(x) (x).begin(), (x).end()
  6. typedef vector<int> vi;
  7. typedef vector<vi> vvi;
  8. typedef vector<pair<int, int>> vpi;
  9. typedef pair<int, int> pi;
  10. #define f first
  11. #define s second
  12. #define pb push_back
  13. #define endl "\n"
  14. #define yes cout << "YES" << endl
  15. #define no cout << "NO" << endl
  16. #define init(x, a) memset(x, a, sizeof(x))
  17. const int mod1 = 1e9 + 7, mod2 = 998244353, INF = 2e18, N = 2e5 + 5, L = 19;
  18. int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); }
  19. // -----------------------------------------------------------------------------
  20.  
  21. void solve()
  22. {
  23.     int n;
  24.     cin >> n;
  25.     string s;
  26.     cin >> s;
  27.     vi p(n);
  28.     for (int i = 0; i < n; i++)
  29.     {
  30.         cin >> p[i];
  31.         p[i]--;
  32.     }
  33.     int ans = 1;
  34.     // we have to find minimum k such that s= s[k:] + s[:k], minimum cyclic shift
  35.     function<int(string &)> cycle = [&](string &s)
  36.     {
  37.         int n = s.size();
  38.         for (int i = 1; i <= n; i++)
  39.         {
  40.             // s[i:] + s[:i], (i to end + 0 to i)
  41.             if (s == s.substr(i) + s.substr(0, i))
  42.             {
  43.                 return i;
  44.             }
  45.         }
  46.         return n;
  47.     };
  48.     vi vis(n, 0);
  49.     // permutaion cycle, all cycles are disjoint, and are shifted
  50.     for (int i = 0; i < n; i++)
  51.     {
  52.         if (vis[i])
  53.         {
  54.             continue;
  55.         }
  56.         int x = i;
  57.         string temp;
  58.         while (!vis[x])
  59.         {
  60.             vis[x] = 1;
  61.             temp += s[x];
  62.             x = p[x];
  63.         }
  64.         // permuatation cycle got
  65.         int shift = cycle(temp);
  66.         ans /= gcd(ans, shift);
  67.         ans *= shift;
  68.     }
  69.     cout << ans << endl;
  70.     return;
  71. }
  72.  
  73. signed main()
  74. {
  75.     // __START__;
  76.     ios_base::sync_with_stdio(false);
  77.     cin.tie(NULL);
  78.     cout.tie(NULL);
  79.     int t = 1;
  80.     cin >> t;
  81.     while (t--)
  82.     {
  83.         solve();
  84.     }
  85.     // __END__;
  86.     return 0;
  87. }
Advertisement
Add Comment
Please, Sign In to add comment