AcWing 3579. 数字移动
原题链接
困难
#include<bits/stdc++.h>
using namespace std;
int n;
int p[200010];
int res[200010];
int main() {
int t;
scanf("%d",&t);
while(t -- ) {
scanf("%d",&n);
for(int i = 1;i <= n;i ++ ) {
scanf("%d",&p[i]);
res[i] = 0;
}
for(int i = 1;i <= n;i ++ ) {
if(!res[i]) {
int head = i,now = p[i];
int cnt = 1;
while(now != head) {
now = p[now];
cnt ++ ;
}
now = p[i];
res[i] = cnt;
while(now != head) {
res[now] = cnt;
now = p[now];
}
}
}
for(int i = 1;i <= n;i ++ ) {
if(i > 1) printf(" ");
printf("%d",res[i]);
}
printf("\n");
}
}