当前位置: 移动技术网 > 移动技术>移动开发>IOS > luogu 1575

luogu 1575

2020年08月10日  | 移动技术网移动技术  | 我要评论

题目

这题是表达式求值的弱化版,先从简单的坐起吧。

首先我们可以发现,or的优先级是最低的,一旦出现or,左边的值立刻就可以先计算了。按照这个思路,一旦一个优先级高的运算符后面有一个优先级低的运算符,那我们就先把优先级高的都算好了,再去算优先级低的,这样能保证答案是正确的。

#include<cstdio>
#include<algorithm>
#include<cstring>
#include<iostream>
#include<vector>
#include<cmath>
#include<map> 
#include<string>
#include<queue>
#include<stack> 
//#define int long long
using namespace std;
stack<int>s;
stack<bool>ans;
void dealp()
{
	if(s.top()==3)
	{
		if(ans.empty())
		{
			cout<<"error";
			exit(0);
		}
		bool flag=ans.top();
		flag=!flag;
		ans.pop();
		ans.push(flag);
	}
	else if(s.top()==2)
	{
		if(ans.size()<2)
		{
			cout<<"error";
			exit(0);
		}
		bool flag=ans.top();
		ans.pop();
		flag=flag and ans.top();
		ans.pop();
		ans.push(flag);
	}
	else if(s.top()==1)
	{
		if(ans.size()<2)
		{
			cout<<"error";
			exit(0);
		}
		bool flag=ans.top();
		ans.pop();
		flag=flag or ans.top();
		ans.pop();
		ans.push(flag);
	}
	s.pop();
}
int main()
{
	ios::sync_with_stdio(false);
	string ss;
	while(cin>>ss)
	{
		if(ss=="not")
		{
			s.push(3);
		}
		else if(ss=="and")
		{
			while(!s.empty()&&s.top()>=2)dealp();
			s.push(2);
		}
		else if(ss=="or")
		{
			while(!s.empty())dealp();
			s.push(1);
		}
		else if(ss=="true")
		{
			ans.push(true);
		}
		else if(ss=="false")
		{
			ans.push(false);
		}
	}
	while(!s.empty())dealp();
	if(ans.size()==1)
	{
		if(ans.top()==false)
		{
			cout<<"false";
		}
		else
		{
			cout<<"true";
		}
	}
	else
	{
		cout<<"error";
	}
}

本文地址:https://blog.csdn.net/qq_37073764/article/details/107877182

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网