E- Seven tombs 表达式运算 + DFS
算法:
1.表达式运算
2.DFS枚举
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<iostream> #include<vector> #include<string> #include<math.h> #include<map> #include<set> #include<stack> #include<algorithm> using namespace std; stack<int>OpE;//操作数栈 stack<char>OpR;//运算符栈 //算符间优先级 int Opet[100], hash[100], len1,len2; bool vis; int visit[100]; char str[1000]; char temp[110]; //栈顶优先权 int Pri[8][8] = {{1,1,-1,-1,-1,1,1}, {1,1,-1,-1,-1,1,1}, {1,1,1,1,-1,1,1}, {1,1,1,1,-1,1,1}, {-1,-1,-1,-1,-1,0,0}, {1,1,1,1,1,1,1}, {-1,-1,-1,-1,-1,-1,-2} }; void init( ) { memset(Opet,0,sizeof(Opet)); Opet['+'] = 0,Opet['-'] = 1,Opet['*'] = 2; Opet['/'] = 3,Opet['('] = 4, Opet[')'] = 5; Opet['#'] = 6; } //判断优先级 int jugde( char p, char q) { return Pri[Opet[p]][Opet[q]]; } int solve(char *str2) { char str1[120]; strcpy(str1,str2); int len = strlen(str1), x, y, i = 0, j; char Op = 0, tp[110]; while( !OpE.empty( ) ) OpE.pop(); while( !OpR.empty() ) OpR.pop(); OpR.push('#'); bool f = true; str1[len] = '#'; while( i <= len && f) { if( str1[i] >= 'A' && str1[i] <= 'G' ) //操作数直接入栈 { int ans = 0; for(j = i; j < len; j++) if( str1[j] >= 'A' && str1[j] <= 'G' ) tp[ans++] = hash[str1[j]] + '0'; else break; i = j; tp[ans] = '\0'; OpE.push(atoi(tp)); } else { switch( jugde(OpR.top(),str1[i]) ) { case 0: OpR.pop();i++;break; case 1: { Op = OpR.top( ); OpR.pop(); x = OpE.top(); OpE.pop(); y = OpE.top( ); OpE.pop( ); if( Op == '+' ) OpE.push( x + y ); else if( Op == '-' ) OpE.push( y - x ); else if( Op == '*' ) OpE.push( y * x ); else if( Op == '/' ) OpE.push( y / x ); break; } case -1: OpR.push(str1[i]);i++;break; case -2: f = false;break; } } } return OpE.top(); } void DFS(int num) { if( vis ) return; if( num == 7 ) { int x = solve(str); int y = solve(temp); if( x == y) { vis = true; for( int i = 0; i < len1; i++) if( str[i] >= 'A' && str[i] <= 'G' ) printf("%d",hash[str[i]]); else printf("%c",str[i]); printf("="); for( int i = 0; i < len2; i++) if( temp[i] >= 'A' && temp[i] <= 'G' ) printf("%d",hash[temp[i]]); else printf("%c",temp[i]); puts(""); } return; } for( int i = 1; i <= 7; i++) { if( !visit[i] ) { visit[i] = 1; hash[num+'A'] = i; DFS(num + 1); visit[i] = 0; if( vis ) return; } } } int main( ) { init( ); while( scanf("%s",str) != EOF ) { vis = false; memset(visit,0,sizeof(visit)); memset(hash,0,sizeof(hash)); char *p = strtok(str,"="); strcpy(str,p); p = strtok(NULL,"="); strcpy(temp,p); len1 = strlen(str); len2 = strlen(temp); DFS(0); } return 0; }
posted on 2012-08-21 16:30 more think, more gains 阅读(198) 评论(0) 编辑 收藏 举报