Why is there a space between this small and Y, which can't be found in the prefix query website every time
First, a point with degree = 3 cannot be a leaf node
The left most leaf node is the first place of the middle order traversal of this tree, so we can determine the number of this leaf node by DP. Let f[i]f[i]f[i] represent the first possible number of the middle order traversal in the subtree of point iii
After determining the first bit of the final middle order traversal, you can expand up through this point
Specifically, if there is only one subtree at this point, judge whether this point and the size of the fff of the subtree are placed at this point, right or father
If there are two subtrees, let's put the right son of the fff small and the father of the fff big. We also need to compare them with the root node and discuss them
Code:
#include<bits/stdc++.h> using namespace std; inline int read(){ int res=0,f=1;char ch=getchar(); while(!isdigit(ch)) {if(ch=='-') f=-f;ch=getchar();} while(isdigit(ch)) {res=(res<<1)+(res<<3)+(ch^48);ch=getchar();} return res*f; } const int N=1000010; int n,m,d[N],rt,st; int ls[N],rs[N]; int lc[N],rc[N],f[N]; int vis[N<<1],head[N<<1],nxt[N<<1],tot=0; void add(int x,int y){vis[++tot]=y;nxt[tot]=head[x];head[x]=tot;} void dfs1(int v,int fa){ for(int i=head[v];i;i=nxt[i]){ int y=vis[i]; if(y==fa) continue; if(!lc[v]) lc[v]=y;else rc[v]=y; dfs1(y,v); f[v]=min(f[y],f[v]); } } void find(int v){ if(d[v]==1 && v!=st) {rt=v;return;} else if(v!=st && d[v]==2 || d[v]==1 && v==st){ if(lc[v]<f[lc[v]]) find(lc[v]); else{rt=v;return;} } else{ if(f[lc[v]]>f[rc[v]]) find(lc[v]); else find(rc[v]); } } int dfs2(int v,int fa){ if(d[v]==1 && v!=rt) return v; int tmp=n+1; if(v!=rt && d[v]==2 || v==rt && d[v]==1) tmp=v; for(int i=head[v],now;i;i=nxt[i]){ int y=vis[i]; if(y==fa) continue; if((now=dfs2(y,v))<tmp) rs[v]=ls[v],ls[v]=y,tmp=now; else rs[v]=y; } return tmp; } void put(int v){ if(ls[v]) put(ls[v]); cout<<v<<" "; if(rs[v]) put(rs[v]); } int main(){ int size=100<<20; __asm__ ("movq %0,%%rsp\n"::"r"((char*)malloc(size)+size)); n=read(); for(int i=1;i<=n;i++){ d[i]=read(); for(int x,j=1;j<=d[i];j++) x=read(),add(i,x); if(d[i]<=2) {f[i]=i; if(!st) st=i;} else f[i]=n+1; } dfs1(st,0);find(st);dfs2(rt,0); put(rt); exit(0); return 0; }