就是递归一层一层处理,要把k个从A移动到C,就要把前k-1个移动到B,再把第k个移动到C,再把第k-1个移动到从B移动到C,以此类推
#include <iostream> #include <cstring> #include <algorithm> #include <cstdio> using namespace std; const int maxn=100; typedef long long ll; ll ans; int n; int s[maxn],t[maxn]; long long ff(int *ss,int ii,int tt) { if(ii==0) return 0; if(ss[ii]==tt) return ff(ss,ii-1,tt);//第ii个就在tt return ff(ss,ii-1,6-ss[ii]-tt)+(1LL<<(ii-1));//ss[ii-1]->other,ss[i]->tt,即+1,other->tt,即2^(ii-1)-1 } int main() { int kase=0; while(~scanf("%d",&n)&&n) { kase++; ans=0; for(int i=1;i<=n;i++) scanf("%d",&s[i]); for(int i=1;i<=n;i++) scanf("%d",&t[i]); int k=n; while(k>=1&&s[k]==t[k]) k--; if(k>=1) { int other=6-s[k]-t[k]; ans=ff(s,k-1,other)+ff(t,k-1,other)+1;//具有对称性,就是k-1个从s到other,第k个从s到t,即+1,other再移动到t } printf("Case %d: %lld\n",kase,ans); } return 0; }