分析:
题目分为两部分解决:
首先是K的确定,之后是答案序列的确定,对于K,如果 0 =< K<=n-1,那么,我们很容易证明,b[K+1] < K+1, 所以我们开一个vector<int>mo, 遍历B数组,找到b[i]<i的点把i存入mo中,之后令K的初值是n+1,取mo中元素的最小值减1,就是K的值,之后,求答案序列只要再开一个vector<int>vre[maxn]存入各个点的子节点; ver[b[i]].push_back(i);那么在所有满足b[i] == 0||b[i] == (n+1)的点中,满足vre[ans[i]].size() != 0的点,就是根root,然后对root进行bfs遍历,就可以求出答案序列;
//AC code:
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e5+1000;
int b[maxn];
int vis[maxn];
int fa[maxn];
vector<int>vre[maxn];
void init(int n){
fill(vis, vis + n + 2, 0);
fill(b, b + n + 2, -1);
for(int i = 0; i <= n + 1; i++){
vre[i].clear();
}
}
int main(){
int t;
cin>>t;
while(t--){
vector<int>ans;
vector<int>mo;
queue<int>q;
int n;
cin>>n;
init(n);
int k;
for(int i = 1; i <= n; i++){
scanf("%d", &b[i]);
if(b[i] == 0 || b[i] == n + 1){
ans.push_back(i);
vis[i] = 1;
}
if(b[i] < i) mo.push_back(i);
if(b[i] > i && b[i] != n+1) mo.push_back(b[i]);
vre[b[i]].push_back(i);
}
k = n+1;
for(auto x:mo) k = min(k, x);
cout<<k-1<<endl;
int root = -1; int rp = -1;
for(int i = 0; i < ans.size(); i++){
if(vre[ans[i]].size() != 0){
root = ans[i];
rp = i;
break;
}
}
if(root == -1){
for(int i = 0; i < ans.size(); i++){
cout<<ans[i]<<" ";
}printf("\n");
continue;
}
swap(ans[rp], ans[ans.size() - 1]);
q.push(root);
while(!q.empty()){
vis[q.front()] = 1;
int u = q.front();
q.pop();
int rs = -1;
for(int i = 0; i < vre[u].size(); i++){
if(!vis[vre[u][i]]) {
if(vre[vre[u][i]].size() != 0&&rs == -1){
rs = vre[u][i];
continue;
}
ans.push_back(vre[u][i]);
q.push(vre[u][i]);
}
}
if(rs != -1){
q.push(rs);
ans.push_back(rs);
}
}
for(int i = 0; i < ans.size(); i++){
cout<<ans[i]<<" ";
}cout<<endl;
}
return 0;
}