# 【BZOJ 1019】【SHOI2008】汉诺塔（待定系数法递推）

## 1019: [SHOI2008]汉诺塔

Time Limit: 1 Sec  Memory Limit: 162 MB
Submit: 559  Solved: 341
[Submit][Status]

## Sample Input

3
AB BC CA BA CB AC

7

## Source

[Submit][Status]

code:

 1 #include<cstdio>
2 #include<cstring>
3 #include<algorithm>
4 #include<vector>
5 #include<string>
6 using namespace std;
7 long long f[35];
8 char s[7][3];
9 int stack[4][6],len[4],m,n;
10 int dfs(int k,char c)
11 {
12     if(len[1]==0&&len[2]==0) return k-1;
13     if(len[1]==0&&len[3]==0) return k-1;
14     for(int i=1;i<=6;++i)
15         if(s[i][0]!=c||k==1)
16         {
17             int x,y;
18             if(s[i][0]=='A') x=1;if(s[i][0]=='B') x=2;if(s[i][0]=='C') x=3;
19             if(s[i][1]=='A') y=1;if(s[i][1]=='B') y=2;if(s[i][1]=='C') y=3;
20             if(len[x]<=0) continue;
21             if(stack[x][len[x]]>stack[y][len[y]]&&len[y]>0) continue;
22             --len[x],++len[y];
23             stack[y][len[y]]=stack[x][len[x]+1];
24             return dfs(k+1,s[i][1]);
25         }
26     return 0;
27 }
28 int main()
29 {
30     freopen("ce.in","r",stdin);
31     freopen("ce.out","w",stdout);
32     scanf("%d\n",&m);
33     for(int i=1;i<=6;++i)
34         for(int j=0;j<=2;++j) scanf("%c",&s[i][j]);
35     memset(len,0,sizeof(len));
36     memset(stack,0,sizeof(stack));
37     stack[1][1]=1,len[1]=1;
38     f[1]=dfs(1,'D');
39     memset(len,0,sizeof(len));
40     memset(stack,0,sizeof(stack));
41     stack[1][1]=2,stack[1][2]=1,len[1]=2;
42     f[2]=dfs(1,'D');
43     memset(len,0,sizeof(len));
44     memset(stack,0,sizeof(stack));
45     stack[1][1]=3,stack[1][2]=2,stack[1][3]=1,len[1]=3;
46     f[3]=dfs(1,'D');
47     memset(len,0,sizeof(len));
48     memset(stack,0,sizeof(stack));
49     stack[1][1]=4,stack[1][2]=3,stack[1][3]=2,stack[1][4]=1,len[1]=4;
50     f[4]=dfs(1,'D');
51     memset(len,0,sizeof(len));
52     memset(stack,0,sizeof(stack));
53     stack[1][1]=5,stack[1][2]=4,stack[1][3]=3,stack[1][4]=2,stack[1][5]=1,len[1]=5;
54     f[5]=dfs(1,'D');
55     int a=(f[5]-f[4])/(f[4]-f[3]);
56     int b=f[4]-a*f[3];
57     for(int i=6;i<=m;++i) f[i]=a*(f[i-1])+b;
58     printf("%lld",f[m]);
59     return 0;
60 }
View Code

posted @ 2014-01-05 22:06  Chellyutaha  阅读(207)  评论(0编辑  收藏