Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- // #include <atcoder/all>
- using namespace std;
- #define int long long
- #define all(x) (x).begin(), (x).end()
- typedef vector<int> vi;
- typedef vector<vi> vvi;
- typedef vector<pair<int, int>> vpi;
- typedef pair<int, int> pi;
- #define f first
- #define s second
- #define pb push_back
- #define endl "\n"
- #define yes cout << "YES" << endl
- #define no cout << "NO" << endl
- #define init(x, a) memset(x, a, sizeof(x))
- const int mod1 = 1e9 + 7, mod2 = 998244353, INF = 2e18, N = 2e5 + 5, L = 19;
- int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); }
- // -----------------------------------------------------------------------------
- void solve()
- {
- int n;
- cin >> n;
- string s;
- cin >> s;
- vi p(n);
- for (int i = 0; i < n; i++)
- {
- cin >> p[i];
- p[i]--;
- }
- int ans = 1;
- // we have to find minimum k such that s= s[k:] + s[:k], minimum cyclic shift
- function<int(string &)> cycle = [&](string &s)
- {
- int n = s.size();
- for (int i = 1; i <= n; i++)
- {
- // s[i:] + s[:i], (i to end + 0 to i)
- if (s == s.substr(i) + s.substr(0, i))
- {
- return i;
- }
- }
- return n;
- };
- vi vis(n, 0);
- // permutaion cycle, all cycles are disjoint, and are shifted
- for (int i = 0; i < n; i++)
- {
- if (vis[i])
- {
- continue;
- }
- int x = i;
- string temp;
- while (!vis[x])
- {
- vis[x] = 1;
- temp += s[x];
- x = p[x];
- }
- // permuatation cycle got
- int shift = cycle(temp);
- ans /= gcd(ans, shift);
- ans *= shift;
- }
- cout << ans << endl;
- return;
- }
- signed main()
- {
- // __START__;
- ios_base::sync_with_stdio(false);
- cin.tie(NULL);
- cout.tie(NULL);
- int t = 1;
- cin >> t;
- while (t--)
- {
- solve();
- }
- // __END__;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment