1. 程式人生 > >NYOJ 1272 表示式求值 (字串處理)

NYOJ 1272 表示式求值 (字串處理)

表示式求值

時間限制:1000 ms  |  記憶體限制:65535 KB 難度:3
描述
假設表示式定義為: 1. 一個十進位制的正整數 X 是一個表示式。 2. 如果 X 和 Y 是 表示式,則 X+Y, X*Y 也是表示式; *優先順序高於+. 3. 如果 X 和 Y 是 表示式,則 函式 Smax(X,Y)也是表示式,其值為:先分別求出 X ,Y 值的各位數字之和,再從中選最大數。 4.如果 X 是 表示式,則 (X)也是表示式。 例如: 表示式 12*(2+3)+Smax(333,220+280) 的值為 69。 請你程式設計,對給定的表示式,輸出其值。  
輸入
【標準輸入】 第一行: T 表示要計算的表示式個數 (1≤ T ≤ 10) 接下來有 T 行, 每行是一個字串,表示待求的表示式,長度<=1000
輸出
【標準輸出】 對於每個表示式,輸出一行,表示對應表示式的值。
樣例輸入
3
12+2*3
12*(2+3)
12*(2+3)+Smax(333,220+280)
樣例輸出
18
60
69

思路:不管Smax,把‘,’當做一種新的運算代替Smax,推出優先順序表就好做了。。

程式碼:

#include<stdio.h>
#include<stack>
#include<string.h> 
using namespace std;
char ope[10]="+-*,()#";
char prec[10][8]={
				//   +-*,()#    //運算子優先順序 
		            ">><><>>",
		            ">><><>>",
		            ">>>><>>",
		            "<<<><>>",
		            "<<<<<=>",
		            ">>>>=>>",
		            "<<<<<<=", 
                };
int getNum(char c)
{
	for(int i=0;i<strlen(ope);i++)
	{
		if(ope[i]==c) return i;
	}
}
char getPrec(char a,char b)//返回a,b優先順序 
{
	int x=getNum(a);
	int y=getNum(b);
	return prec[x][y]; 
}
int mod(int n)//取餘求和 
{
	int sum=0;
	while(n>0)
	{
		sum+=n%10;
		n=n/10;
	}
	return sum;
}
int caculate(int a,int b,char threat)//計算 
{
	  switch(threat)
	  {
	  	case '+': return a+b;
	  	case '-': return a-b;
	  	case '*': return a*b;
	  	case ',': return mod(a)>mod(b)?mod(a):mod(b); 
	  } 
 } 
int main()
{  
    int t;
	scanf("%d",&t);
	char str[1050];
	stack<int>num;
	stack<char> op;
	while(t--)
	{
	    scanf("%s",str);
		op.push('#');
	    int len=strlen(str);
	    str[len]='#';
	    str[len+1]='\0';
	    len++;
	    bool input=false;//標記接受數字 
	    int temp=0;
		for(int i=0;i<len;i++)
		{
		   if(str[i]>='0'&&str[i]<='9')//處理數字 
		   {
		         input=true;
				 temp=temp*10+str[i]-'0';
		   }
		   else if(str[i]=='+'||str[i]=='-'||str[i]==','||str[i]=='*'||str[i]=='('||str[i]==')'||str[i]=='#')
		   {
		      if(input)//沒有接收數字就不push 
			  {
			  	num.push(temp);
		        temp=0;
		        input=false;
			  }
			  int flag=true;//當棧頂元素優先順序大於str[i]時,一直運算 
			  while(flag)
			  {
				  	switch(getPrec(op.top(),str[i]))
					  {
					  	case '<': op.push(str[i]);flag=false;break;//棧頂元素優先順序低,運算子入棧 
					  	case '=': op.pop();flag=false;break;//去括號 
					  	case '>': {
					  		        int a=num.top();num.pop();
					  		        int b=num.top();num.pop();
					  		        char threat=op.top();op.pop();
					  		    //     printf("%d %c %d\n",a,threat,b);
					  		        num.push(caculate(a,b,threat));
							 		break;
								  }
					  }
			  }
				  
		   }
		
		}	
        printf("%d\n",num.top());//輸出棧頂元素 
    	num.pop();
	}	
}