POJ 3295 Tautology

虽然AC了,但是要做深刻的总结。

View Code
  1 /*首先需要考虑五个问题。
2 第一:怎样遍历p,q,r,s,t分别取0,1?用个数组value[5],根据value[i]分别取0,1,可以五重循环实现,也可以递归实现。注意递归实现的技巧。
3 第二:如何判断真值?有了p,q,r,s,t的值以后,则用计算前缀表达式的方法来处理。注意这种情况也能递归。根据每次value的值,如果返回值为1,则真,继续换下一种;返回为0,则不用计算了,打印not。*/
4
5 #include<string.h>
6 #include<iostream>
7 using namespace std;
8
9 const int K=0;
10 const int A=1;
11 const int N=2;
12 const int C=3;
13 const int E=4;
14 const int LEN=101;
15
16 int definition[5][4]={{0,0,0,1},{0,1,1,1},{1,0,0,0},{1,1,0,1},{1,0,0,1}};
17 int value[5]={0};
18 int stack[LEN];
19 string WFF;
20
21 int exp()
22 {
23 int len=WFF.length();
24 int top=0;
25
26 for(int i=len-1;i>=0;i--)
27 {
28 if(WFF[i]=='K')
29 {
30 int index=(stack[top]<<1)^stack[top-1];
31 stack[--top]=definition[K][index];
32 continue;
33 }
34 if(WFF[i]=='A')
35 {
36 int index=(stack[top]<<1)^stack[top-1];
37 stack[--top]=definition[A][index];
38 continue;
39 }
40 if(WFF[i]=='N')
41 {
42 stack[top]=definition[N][stack[top]];
43 continue;
44 }
45 if(WFF[i]=='C')
46 {
47 int index=(stack[top]<<1)^stack[top-1];
48 stack[--top]=definition[C][index];
49 continue;
50 }
51 if(WFF[i]=='E')
52 {
53 int index=(stack[top]<<1)^stack[top-1];
54 stack[--top]=definition[E][index];
55 continue;
56 }
57 else
58 {
59 stack[++top]=value[WFF[i]-'p'];
60 }
61 }
62
63 return stack[top];
64
65 }
66
67
68 int calvalue(int step)
69 {
70 if(step==5)
71 {
72 return exp();
73 }
74 value[step]=0;
75 if(calvalue(step+1) ==0)
76 return 0;
77 value[step]=1;
78 if(calvalue(step+1) ==0)
79 return 0;
80 return 1;
81
82 }
83
84
85 void read()
86 {
87 while(1)
88 {
89 cin>>WFF;
90 if(WFF[0]!='0')
91 {
92
93 if(calvalue(0)==1)
94 cout<<"tautology"<<endl;
95 else
96 cout<<"not"<<endl;
97 }
98 else
99 return ;
100 }
101
102 }
103
104 int main()
105 {
106 read();
107 return 0;
108 }

附加一个递归的测试程序。。。

View Code
 1 #include<iostream>
2 using namespace std;
3
4 int a[5];
5 void show()
6 {
7 for(int i=0;i<=4;i++)
8 cout<<a[i];
9 cout<<endl;
10 }
11
12 int cal(int step)
13 {
14 if(step == 5)
15 {
16 show();
17 return 1;
18 }
19 a[step]=0;
20 int j=cal(step+1);
21 cout<<j<<endl;
22 a[step]=1;
23 int h=cal(step+1);
24 cout<<"ssssssssssssssssssssssssss"<<h<<endl;
25 }
26
27 int main()
28 {
29 cal(0);
30 return 0;
31 }



posted @ 2011-10-16 22:01  YipWingTim  阅读(190)  评论(0编辑  收藏  举报