POJ 1472 Instant Complexity

模拟题:递归求解,有点像语法分析器

代码
1 #include <iostream>
2  using namespace std;
3  char ch[10];
4  int solve(int* exps)
5 {
6 scanf("%s", ch);
7 if(ch[0]=='E')return 0;
8 if(ch[0]=='B')
9 while(solve(exps));
10 else if(ch[0]=='L')
11 {
12 scanf("%s", ch);
13 int i,s,t = -1,texps[11]={0};
14 if(ch[0]!='n')t=atoi(ch);
15 while(solve(texps));
16 if(t==-1){
17 for(i=10;i>0;i--)texps[i]=texps[i-1];
18 texps[0]=0;
19 }
20 else
21 for(i=0;i<11;i++)texps[i]*=t;
22 for(i=0;i<11;i++)exps[i]+=texps[i];
23 }
24 else
25 {
26 scanf("%s", ch);
27 exps[0]+=atoi(ch);
28 return solve(exps);
29 }
30 return 1;
31 }
32 int main()
33 {
34 int n,i,j,t, exps[11];
35 scanf("%d", &n);
36 for(i=1;i<=n;i++)
37 {
38 memset(exps, 0, sizeof(exps));
39 solve(exps);
40 printf("Program #%d\nRuntime = ", i);
41 for(t=0,j=10;j>=0;j--)
42 if(exps[j]!=0)
43 {
44 t++;
45 if(t!=1)printf("+");
46 if(exps[j]!=1||j==0)printf("%d", exps[j]);
47 if(exps[j]!=1&&j>0)printf("*");
48 if(j>1)printf("n^%d", j);
49 if(j==1)printf("n");
50 }
51 if(!t)printf("0");
52 printf("\n\n");
53 }
54 return 0;
55 }

 

 

posted on 2011-01-17 21:00  ltang  阅读(573)  评论(1编辑  收藏  举报

导航