这个题关键是想明白,K的含义,即,向前跃进几步
代码如下
1 #include<bits/stdc++.h> 2 using namespace std; 3 #define inf 1000000000 4 #define maxn 200005 5 vector<int> d[maxn]; 6 int p[maxn], c[maxn]; 7 bool vis[maxn]; 8 int cal(vector<int> loop) 9 { 10 int minn = inf; 11 for(int k = 0; k < d[loop.size()].size(); k++){ 12 int len = d[loop.size()][k]; 13 for(int i = 0; i < len; i++){ 14 bool flag = true; 15 for(int j = i; j < loop.size(); j += len){ 16 if(c[loop[i]] != c[loop[j]]){ 17 flag = false; 18 break; 19 } 20 } 21 if(flag) minn = min(minn, len); 22 } 23 24 } 25 return minn; 26 } 27 int main() 28 { 29 for(int i = 1; i <= maxn; i++) 30 for(int j = i; j < maxn; j+= i) 31 d[j].push_back(i); 32 int t; 33 cin >> t; 34 while(t--){ 35 int n; 36 cin >> n; 37 for(int i = 1; i <= n; i++) cin >> p[i]; 38 for(int i = 1; i <= n; i++) cin >> c[i]; 39 for(int i = 0; i <= n; i++) vis[i] = false; 40 int ans = n; 41 for(int i = 1; i <= n; i++){ 42 if(vis[i]) continue; 43 int k = i; 44 vector<int> loop; 45 while(!vis[k]){ 46 loop.push_back(k); 47 vis[k] = true; 48 k = p[k]; 49 } 50 ans = min(ans, cal(loop)); 51 } 52 cout << ans << endl; 53 54 } 55 }