二十四点(2019-03)

#include<bits/stdc++.h>
using namespace std;
stack<int>num;
stack<char>op;
void eval(){
	int b=num.top();num.pop();
	int a=num.top();num.pop();
	char c=op.top();op.pop();
	int x;
	if(c=='+')x=a+b;
	else if(c=='-')x=a-b;
	else if(c=='x')x=a*b;
	else{
		if(a*b>=0)x=a/b;
		else{
			if(a%b==0)x=a/b;
			else x=a/b-1;
		}
	}
	num.push(x);
}
int main(){
	unordered_map<char,int>pr;
	pr['+']=pr['-']=1;
	pr['x']=pr['/']=2;
	int n;
	cin>>n;
	while(n--){
		string str;
		cin>>str;
		num=stack<int>();
		op=stack<char>();
		for(auto c:str)
		if(c>='1'&&c<='9')num.push(c-'0');
		else{
			while(op.size()&&pr[op.top()]>=pr[c])eval();
			op.push(c);
		}
		while(op.size())eval();
		if(num.top()==24)puts("Yes");
		else puts("No");
	}
	return 0;
}

第二次复习

#include<bits/stdc++.h>
using namespace std;
map<char,int>mp;
int al(char t,stack<int>&num,stack<char>&op){
	int k1=num.top();num.pop();
	int k2=num.top();num.pop();
	
		if(t=='+')return k1+k2;
		if(t=='-')return k2-k1;
		if(t=='x')return k1*k2;
		if(t=='/')return k2/k1;
	
}
void oper(string str,stack<int>num,stack<char>op){
	for(auto t:str){
		if(t>='0'&&t<='9'){
			num.push(t-'0');
		}else{
			if(!op.empty()){
				if(mp[t]<=mp[op.top()]){
					int m=al(op.top(),num,op);
					op.pop();
					op.push(t);
					num.push(m);
				}else{
					op.push(t);
				}
			}else op.push(t);
		}
	}
	while(!op.empty()){
		int k1=num.top();num.pop();
		int k2=num.top();num.pop();
		int k=0;
		char t=op.top();op.pop();
		if(t=='+')k=k1+k2;
		if(t=='-')k=k2-k1;
		if(t=='x')k=k1*k2;
		if(t=='/')k=k2/k1;
		num.push(k);
	}
	if(num.top()==24)cout<<"Yes"<<endl;
	else cout<<"No"<<endl;
}
int main(){
	mp['-']=mp['+']=1;
	mp['x']=mp['/']=2;
	int n;
	cin>>n;
	while(n--){
		string str;
		stack<int>num;
		stack<char>op;
		cin>>str;
		oper(str,num,op);
	}
} 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值