题目:http://www.lydsy.com/JudgeOnline/problem.php?id=1078
每一次进入的点一定是一个极左节点,然后将它所处在的整棵树左右翻转。加上一些情况的处理。
#include<cstring> #include<iostream> #include<algorithm> #include<cstdlib> #include<cstdio> #include<cmath> #include<queue> #define rep(i,l,r) for (int i=l;i<=r;i++) #define down(i,l,r) for (int i=l;i>=r;i--) #define clr(x,y) memset(x,y,sizeof(x)) #define maxn 2005 #define eps 1e-3 #define ll long long #define inf (1LL<<50) using namespace std; int fa[maxn],l[maxn],r[maxn],ans[maxn],n,tot,root; int read(){ int x=0,f=1; char ch=getchar(); while (!isdigit(ch)) {if (ch==‘-‘) f=-1; ch=getchar();} while (isdigit(ch)) {x=x*10+ch-‘0‘; ch=getchar();} return x*f; } void solve(){ int x=root; while (r[x]!=-1) x=l[x]; int t=l[x]; if (t!=-1&&l[t]==-1&&r[t]==-1) x=t; ans[++tot]=x; if (x==root) root=l[root]; int f=fa[x]; if (f!=-1) l[f]=l[x],fa[l[f]]=f; while (f!=-1) swap(l[f],r[f]),f=fa[f]; } int main(){ n=read(); fa[0]=-1; clr(l,-1); clr(r,-1); rep(i,1,n) { int x=read(); if (x>=100) fa[i]=x-100,r[x-100]=i; else fa[i]=x,l[x]=i; } rep(i,0,n) solve(); while (tot) printf("%d ",ans[tot--]); return 0; }
时间: 2024-10-12 12:34:29