POJ 2106

题意:bool表达式求值,V:true;F:false

题解:堆栈+优先级判定

View Code
 1 #include<cstdio>

 2 #include<cstring>

 3 #include<algorithm>

 4 #include<cctype>

 5 using namespace std;

 6 const int N=1000;

 7 char comp(char a,char b)

 8 {

 9     if(b=='\0')

10     {

11         if(a=='\0')

12             return '=';

13         else

14             return '>';

15     }

16     else if(a=='\0')

17         return '<';

18     else if(b=='(')

19         return '<';

20     else if(b==')')

21     {

22         if(a=='(')

23             return '=';

24         else

25             return '>';

26     }

27     else if(a=='(')

28         return '<';

29     else

30         return '>';

31 }

32 bool cac(bool a,bool b,char op)

33 {

34     if(op=='|')

35         return a||b;

36     else if(op=='&')

37         return a&&b;

38 }

39 bool solve(char s[])

40 {

41     int len=strlen(s),optop=0,botop=0,i=0;

42     char opstk[N];

43     bool bostk[N];

44     opstk[optop++]='\0';

45     while(s[i]!='\0'||opstk[optop-1]!='\0')

46     {

47         if(s[i]==' '||s[i]=='\t')

48         {

49             i++;

50             continue;

51         }

52         else if(s[i]=='!'||s[i]=='(')

53             opstk[optop++]=s[i++];

54         else if(s[i]=='V'||s[i]=='F')

55             bostk[botop++]=(s[i]=='V'),i++;

56         else

57         {

58             switch(comp(opstk[optop-1],s[i]))

59             {

60                 case '>':

61                     if(opstk[optop-1]=='!')

62                     {

63                         optop--;

64                         bostk[botop-1]^=true;

65                     }

66                     else

67                     {

68                         bool b=bostk[--botop],a=bostk[--botop];

69                         char ch=opstk[--optop];

70                         bostk[botop++]=cac(a,b,ch);

71                     }

72                     break;

73                 case '<':

74                     opstk[optop++]=s[i++];

75                     break;

76                 case '=':

77                     optop--;

78                     i++;

79                     break;

80             }

81         }

82     }

83     return bostk[0];

84 }

85 int main()

86 {

87     char s[200];

88     int ca=0;

89     while(gets(s))

90         printf("Expression %d: %c\n",++ca,solve(s)?'V':'F');

91     return 0;

92 }

你可能感兴趣的:(poj)