一道思维题,我自己没能想出来,研究了很久,最后参考了题解想了很久才做出来,但题解写得比较简略,于是在此记录一下。
解题思路
-
因为是无限延伸的完全二叉树,所以只要不对树根进行U操作,所有的命令都是合法的。
-
因为是无限复读指令,所以每一次执行指令之后的相对的位移是一样的。
-
于是,可以将要遍历的整棵树分成几个相同(也可以有包含关系)且连续的部分(这样可以用重复执行相同指令串来处理),然后处理每一个部分的过程就是要求出的指令串。
-
每一部分的具体操作中一定会遍历起点到终点的边一遍和其他的边两遍,于是有 $tot = 2 \times ( sum - 1 ) - d $( tot 是步骤数, sum 是点数, d 是起点到终点的边数),具体参考图片:


代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
| #include<bits/stdc++.h> using namespace std; const int maxn=2e3+100; int n,l[maxn],r[maxn]; int tmp_l[maxn],tmp_r[maxn];
int sum,cur,ans=0x3f3f3f3f;
char p[maxn];
int read(){ char tmp; int now; cin>>tmp; n++; now=n; if(tmp=='1'||tmp=='3') l[now]=read(); if(tmp=='2'||tmp=='3') r[now]=read(); return now; } void merge(int &x,int y){ if(x==0)sum++,x=sum; if(y==cur)return; if(l[y]!=0)merge(tmp_l[x],l[y]); if(r[y]!=0)merge(tmp_r[x],r[y]); } void solve(int u,int d){ if(u!=1){ memset(tmp_l,0,sizeof(tmp_l)); memset(tmp_r,0,sizeof(tmp_r)); sum=1; cur=1; while(cur){ int t=cur; for(int i=0;i<d;i++){ cur=(p[i]=='l'?l[cur]:r[cur]); } int tmp_x=1; merge(tmp_x,t); } ans=min(ans,(sum-1)*2-d); } p[d]='l'; if(l[u]) solve(l[u],d+1); p[d]='r'; if(r[u]) solve(r[u],d+1); } int main(){ read(); solve(1,0); cout<<ans<<endl; return 0; }
|