zoukankan      html  css  js  c++  java
  • [CF1327D] Infinite Path

    (i)(p[i]) 连边,则在每个长度为 (l) 的环里,我们可以花费 (mathcal{O}(l^2)) 的时间去暴力枚举答案

    而答案 (k) 合法等价于答案 ((k,l)) 合法

    于是我们只需要枚举 (l) 的每个因数即可,复杂度 (mathcal{O}(n sqrt n))

    #include <bits/stdc++.h>
    using namespace std;
    
    #define int long long
    const int N = 1000005;
    
    int t,n,a[N],c[N],v[N],ans;
    
    int check(const vector<int> &vec,const int s) {
        int l=vec.size();
        int *u=new int[l];
        for(int i=0;i<l;i++) u[i]=0;
        for(int i=0;i<l;i++) if(u[i]==0) {
            int p=i;
            int fg=1;
            do {
                u[p]=1;
                if(c[vec[p]]!=c[vec[i]]) fg=0;
                p=(p+s)%l;
            } while(p!=i);
            if(fg) return 1;
        }
        return 0;
    }
    
    signed main() {
        ios::sync_with_stdio(false);
        cin>>t;
        while(t--) {
            cin>>n;
            ans=1e9;
            for(int i=1;i<=n;i++) cin>>a[i];
            for(int i=1;i<=n;i++) cin>>c[i];
            for(int i=1;i<=n;i++) if(v[i]==0) {
                vector <int> vec;
                int p=i;
                do {
                    vec.push_back(p);
                    v[p]=1;
                    p=a[p];
                } while(p!=i);
                int l=vec.size();
                for(int j=1;j*j<=l;j++) if(l%j==0) {
                    if(check(vec,j)) ans=min(ans,j);
                    if(check(vec,l/j)) ans=min(ans,l/j);
                }
            }
            cout<<ans<<endl;
            for(int i=1;i<=n;i++) v[i]=0;
        }
    }
    
    
  • 相关阅读:
    std::string构造函数
    shell命令-while语句
    shell命令-for语句
    shell命令-if语句
    softmax回归推导
    sigmod函数求导
    生成器面试题之一
    range和xrange的区别
    python里的input
    python中print和input的底层实现
  • 原文地址:https://www.cnblogs.com/mollnn/p/12558096.html
Copyright © 2011-2022 走看看