B1 data range is small, can be solved direct violence, a large range of data B2, it is not violent
The meaning of problems
Let beg from $ a [i] $ to \ (i \) after steps
Thinking
The \ (a [i] \ sim i \) as a ring, each of the \ (a [i] \) to \ (I \) number of steps required is the same. (A little thought and investigation set)
E.g
n 5 a[] 5 1 2 4 3 a[1] = 5 a[1] -> a[5] -> a[3] -> a[2] -> a[1] 即 5 3 2 1 5 构成一个环,环内所有数字的步数都相同
Code
#include <bits/stdc++.h>
using namespace std;
int main(){
int q,n;
cin >> q;
while(q--){
cin >> n;
vector<int> a(n+1);
for(int i = 1;i <= n; ++i) cin >> a[i];
vector<int> used(n+1);
vector<int> ans(n+1);
for(int i = 1;i <= n; ++i){
if(!used[i]){
vector<int> cur;// 保存该环内所有的数字
while(!used[i]){
cur.push_back(i);
used[i] = true;
i = a[i];
}
for(auto el : cur) ans[el] = cur.size(); // 环内所有数字的步数 就是 环的大小。
}
}
for(int i = 1;i <= n; ++i) cout << ans[i] <<" ";
cout << endl;
}
return 0;
}