您的位置:首页 > 其它

NYOJ 305 表达式求值 (简单栈应用)

2015-04-17 16:25 429 查看
题意:

求一个表达式的值,这个表达式只有add(a,b),min(a,b),max(a,b)这些函数。

题解:

直接乱搞。注意可能有浮点数。

#include<iostream>
#include<math.h>
#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<vector>
#include<queue>
#include<map>
#include<set>
#include<stack>
#include<string>
#define B(x) (1<<(x))
using namespace std;
typedef long long ll;
void cmax(int &a,int b){ if(b>a)a=b; }
void cmin(int &a,int b){ if(b<a)a=b; }
void cmax(ll &a,ll b){ if(b>a)a=b; }
void cmin(ll &a,ll b){ if(b<a)a=b; }
void add(int &a,int b,int mod){ a=(a+b)%mod; }
void add(ll &a,ll b,ll mod){ a=(a+b)%mod; }
void add(int &a,int b){ a+=b; }
void add(ll &a,ll b){ a+=b; }
const int oo=0x3f3f3f3f;
const ll MOD=1000000007;
char str[305],s[305];
stack<string>op;
stack<double>num;

double calc(double a,double b,string s){
	if(s=="add") return a+b;
	if(s=="max") return max(a,b);
	if(s=="min") return min(a,b);
}

int main(){
	int T;
	scanf("%d",&T);
	while(T--){
		while(!num.empty())num.pop();
		while(!op.empty())op.pop();
		scanf("%s",str);
		for(int i=0;str[i];i++){
			if(isalpha(str[i])){
				int k=0;
				s[k++]=str[i++];
				s[k++]=str[i++];
				s[k++]=str[i++];
				s[k]='\0';
				op.push(s);
			}else if(isdigit(str[i])){
				int k=0;
				for(;str[i]!=','&&str[i]!=')'&&str[i];i++)
					s[k++]=str[i];
				s[k]='\0';
				num.push(atof(s));
				if(str[i]==')')i--;
			}else if(str[i]==')'){
				double a=num.top();num.pop();
				double b=num.top();num.pop(); 
				num.push(calc(a,b,op.top()));
				op.pop();
			}
		}
		while(!op.empty()){
			double a=num.top();num.pop();
			double b=num.top();num.pop(); 
			num.push(calc(a,b,op.top()));
			op.pop();
		}
		cout<<num.top()<<endl;
	}
    return 0;
}
/*
3
add(1.478,2.1245) 
max(1.789,999.45) 
add(min(1.45,1000.787),add(100.123,99.77)) 
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: