Codeforces Round 797 (Div. 3) F. Shifting String

在这里插入图片描述
感觉这种题写多了,第一眼就感觉是个图论,很经典的排列置换问题,首先连边,然后观察样例可以知道,大概是多个环的大小取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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值