感觉这种题写多了,第一眼就感觉是个图论,很经典的排列置换问题,首先连边,然后观察样例可以知道,大概是多个环的大小取lcm,但容易发现,环内部的循环节也对答案有影响,比如一个长度为4的aaaa的环,只需要置换一遍就可以恢复,所以是对每个环内部的循环节取lcm即可。
#include <bits/stdc++.h>
using namespace std;
const int N = 2e3 + 5;
typedef long long ll;
typedef pair<ll, ll> pll;
typedef array<ll, 3> ar;
int mod = 1e9 + 7;
const int maxv = 4e6 + 5;
// #define endl "\n"
int n, m, tot, dfsn[N], ins[N], low[N];
stack<int> s;
vector<int> e[N];
vector<vector<int>> scc;
int b[N];
void dfs(int x)
{
low[x] = dfsn[x] = ++tot, ins[x] = 1, s.push(x);
for (auto u : e[x])
{
if (!dfsn[u])
{
dfs(u);
low[x] = min(low[x], low[u]);
}
else if (ins[u])
low[x] = min(low[x], dfsn[u]);
}
if (dfsn[x] == low[x])
{
vector<int> c;
while (1)
{
auto t = s.top();
c.push_back(t);
ins[t] = 0;
s.pop();
b[t] = scc.size();
if (t == x)
break;
}
scc.push_back(c);
}
}
void add(int u, int v)
{
e[u].push_back(v);
}
vector<int> prefix_function(string s)
{
int n = (int)s.length();
vector<int> pi(n);
for (int i = 1; i < n; i++)
{
int j = pi[i - 1];
while (j > 0 && s[i] != s[j])
j = pi[j - 1];
if (s[i] == s[j])
j++;
pi[i] = j;
}
return pi;
}
void solve()
{
cin>>n;
string s;
cin>>s;
s=" "+s;
vector<int> p(n+5);
for(int i=1;i<=n;i++) cin>>p[i],add(i,p[i]);
for(int i=1;i<=n;i++){
if(!dfsn[i]) dfs(i);
}
ll ans=1;
for(auto v: scc){
string tmp;
for(auto &x: v){
tmp.push_back(s[x]);
}
// cout<<tmp<<endl;
string c=tmp+tmp;
auto x=prefix_function(c);
ll res=c.size()-x[c.size()-1];
ans=lcm(ans,res);
}
cout<<ans<<endl;
tot=0;
scc.clear();
for(int i=1;i<=n;i++){
e[i].clear();
dfsn[i]=low[i]=ins[i]=b[i]=0;
}
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int t;
t = 1;
cin >> t;
while (t--)
{
solve();
}
system("pause");
return 0;
}