水题,表达式问题。 这里主要是用来尝试一下STL中自带的集合的各种操作,包括交,并,差。 #include <cstdio> #include <set> #include <string> #include <iostream> #include <algorithm> #include <iterator> using namespace std; const int MAX = 300; int value[128]; char stack[MAX]; int stacki; string input,postorder; void change() { postorder.clear(); stacki = 0 ; for( int i = 0 ; i != input.size() ; ++i ) if( input[i] == '(' ) stack[ stacki++ ] = -1; else if( input[i] == ')' ) { while( stack[ stacki - 1 ] != -1 ) postorder.push_back(stack[--stacki]); --stacki; } else if( input[i] == '{' ) { for( ; input[i] != '}' ; ++i ) postorder.push_back( input[i] ); postorder.push_back( input[i] ); } else { while( stacki != 0 && stack[ stacki - 1 ] != -1 && value[ stack[ stacki - 1 ] ] >= value[ input[i] ] ) postorder.push_back( stack[ --stacki ] ); stack[ stacki++ ] = input[i]; } while( stacki != 0 ) postorder.push_back( stack[ --stacki ] ); } set<char> getresult() { set<char> stack[MAX]; set<char> mid; stacki = 0 ; for( int i = 0 ; i != postorder.size() ; ++i ) if( postorder[i] == '{' ) { ++i; stack[ stacki ].clear(); for( ; postorder[i] != '}' ; ++i ) stack[ stacki ].insert( postorder[i]); stacki++; } else if( postorder[i] == '-' ) { --stacki ; mid.clear(); set_difference( stack[ stacki - 1 ].begin() , stack[ stacki - 1 ].end() , stack[ stacki ].begin() , stack[ stacki ].end() , inserter( mid , mid.begin() ) ); stack[ stacki - 1 ] = mid; } else if( postorder[i] == '+' ) { --stacki; mid.clear(); set_union( stack[ stacki - 1 ].begin() , stack[ stacki - 1 ].end() , stack[ stacki ].begin() , stack[ stacki ].end() , inserter( mid , mid.begin() ) ); stack[ stacki - 1 ] = mid; } else { --stacki; mid.clear(); set_intersection( stack[ stacki - 1 ].begin() , stack[ stacki - 1 ].end() , stack[ stacki ].begin() , stack[ stacki ].end() , inserter( mid , mid.begin() ) ); stack[ stacki - 1 ] = mid; } return stack[0]; } int main() { value['+'] = value['-'] = 0; value['*'] = 1; while( cin>>input ) { change(); set<char> result = getresult(); printf("{"); for( set<char>::iterator i = result.begin() ; i != result.end() ; ++i ) printf("%c",*i); printf("}/n"); } return 0; }