NYOJ305(递归)
解题思路:这是道表达式求值问题,只需考虑加法(add)、求最大值(max)以及最小值(min),可以用递归简单实现。注意括号和逗号的处理。
View Code
1 #include<iostream>
2 #include<cstdio>
3 using namespace std;
4
5 char str[1000];
6 int start;
7
8 int min(int a,int b)
9 {
10 if(a<b) return a;
11 else return b;
12 }
13 int max(int a,int b)
14 {
15 if(a<b) return b;
16 else return a;
17 }
18 int Solve()
19 {
20 int n,v;
21 switch(str[start])
22 {
23 case 'm': start+=3;
24 if(str[start-2]=='i')
25 return min(Solve(),Solve());
26 else return max(Solve(),Solve());
27 case 'a': start+=3;
28 return Solve()+Solve();
29 case '(':
30 case ')':
31 case ',': start++;
32 return Solve();
33 default:
34 sscanf(str+start,"%d%n",&v,&n);//从字符数组start位置开始读入n位的数字v
35 start+=n;
36 return v;
37 }
38 }
39
40 int main()
41 {
42 int n;
43 scanf("%d",&n);
44 while(n--)
45 {
46 scanf("%s",str);
47 start=0;
48 printf("%d\n",Solve());
49 }
50 return 0;
51 }
2 #include<cstdio>
3 using namespace std;
4
5 char str[1000];
6 int start;
7
8 int min(int a,int b)
9 {
10 if(a<b) return a;
11 else return b;
12 }
13 int max(int a,int b)
14 {
15 if(a<b) return b;
16 else return a;
17 }
18 int Solve()
19 {
20 int n,v;
21 switch(str[start])
22 {
23 case 'm': start+=3;
24 if(str[start-2]=='i')
25 return min(Solve(),Solve());
26 else return max(Solve(),Solve());
27 case 'a': start+=3;
28 return Solve()+Solve();
29 case '(':
30 case ')':
31 case ',': start++;
32 return Solve();
33 default:
34 sscanf(str+start,"%d%n",&v,&n);//从字符数组start位置开始读入n位的数字v
35 start+=n;
36 return v;
37 }
38 }
39
40 int main()
41 {
42 int n;
43 scanf("%d",&n);
44 while(n--)
45 {
46 scanf("%s",str);
47 start=0;
48 printf("%d\n",Solve());
49 }
50 return 0;
51 }