标签:
Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 305 Accepted Submission(s): 146
一个环的问题,根据题意可知,出现环answer += len() - 1;没有环,则answer += len();并且若没有环即上下数字相同,即len() = 1;简单的搜索一下环就可以了。
#include<cstdio> #include<cstring> #include<algorithm> const int maxn = 1e5+5; using namespace std; int a[maxn]; int b[maxn]; int sum[maxn]; bool vis[maxn]; int main(){ int T; scanf("%d",&T); while(T--){ int n; scanf("%d",&n); for(int i = 1; i <= n; i++){ scanf("%d",&a[i]); } for(int i = 1; i <= n; i++){ scanf("%d",&b[a[i]]); } for(int i = 1; i <= n; i++){ vis[i] = 0; } int ans = 0; for(int i = 1; i <= n; i++){ int x = a[i]; if(vis[x])continue; int cnt = 0; while(!vis[x]){ vis[x] = 1; x = b[x]; cnt++; } if(cnt == 1)ans++; else ans += cnt-1; } printf("%d\n",ans); } return 0; }
标签:
原文地址:http://www.cnblogs.com/ACMessi/p/4854631.html