社区讨论

0 pts TLE 求调

P2186小 Z 的栈函数参与者 1已保存回复 0

讨论操作

快速查看讨论及其快照的属性,并进行相关操作。

当前回复
0 条
当前快照
1 份
快照标识符
@mjsjdxga
此快照首次捕获于
2025/12/30 20:01
2 个月前
此快照最后确认于
2025/12/30 22:21
2 个月前
查看原帖
CPP
#include<bits/stdc++.h>
using namespace std;
string step[2010];
long long num[2010],tot;
stack<long>st;
long long error()
{
	cout<<"ERROR"<<endl;
	return 11111111;
}
inline long long read()
{
    long long s=0,w=1;
    char ch=getchar();
    while(ch<'0'||ch>'9')
	{
		if(ch=='-') w=-1;
		ch=getchar();
	}
    while(ch>='0'&&ch<='9')
    {
		s=s*10+(ch-'0');
		ch=getchar();
    }
    return s*w;
}
bool check(long long x)
{
	if(abs(x)>1000000000)
		return false;
	else return true;
		
}
long solve(int x)
{
	if(!st.empty()) st.pop();
	st.push(x);
	for(int i=1;i<tot;i++)
	{
		if(step[i]=="NUM")
		{
			if(check(num[i]))
			{
				st.push(num[i]);
			}
			else return error();
		}
		if(step[i]=="POP")
		{
			if(st.empty()) return error();
			st.pop();
		}
		if(step[i]=="INV")
		{
			if(st.empty()) return error();
			long long k;
			k=st.top();
			st.pop();
			st.push(-k);
		}
		if(step[i]=="DUP")
		{
			if(st.empty()) return error();
			st.push(st.top());
		}
		if(step[i]=="SWP")
		{
			if(st.size()<2) return error();
			long long k,k1;
			k=st.top();
			st.pop();
			k1=st.top();
			st.pop();
			st.push(k);
			st.push(k1);
		}
		if(step[i]=="ADD")
		{
			if(st.size()<2) return error();
			long long k,k1;
			k=st.top();
			st.pop();
			k1=st.top();
			st.pop();
			if(check(k+k1))
				st.push(k+k1);
			else return error();
		}
		if(step[i]=="SUB")
		{
			if(st.size()<2) return error();
			long long k,k1;
			k=st.top();
			st.pop();
			k1=st.top();
			st.pop();
			if(check(k1-k))
				st.push(k1-k);
			else return error();
		}
		if(step[i]=="MUL")
		{
			if(st.size()<2) return error();
			long long k,k1;
			k=st.top();
			st.pop();
			k1=st.top();
			st.pop();
			if(check(k*k1))
				st.push(k*k1);
			else return error();
		}
		if(step[i]=="DIV")
		{
			if(st.size()<2) return error();
			long long k,k1;
			k=st.top();
			st.pop();
			k1=st.top();
			st.pop();
			if(k==0) return error();
			if(check(k1/k))
				st.push(k1/k);
			else return error();
		}
		if(step[i]=="MOD")
		{
			if(st.size()<2) return error();
			long long k,k1;
			k=st.top();
			st.pop();
			k1=st.top();
			st.pop();
			if(check(k1%k))
				st.push(k1%k);
			else return error();
		}
		if(st.size()!=1) return error();
		else return st.top();
	}
}
int main()
{
	int n;
	for(tot=1;;tot++)
	{
		cin>>step[tot];
		if(step[tot]=="END") break;
		else if(step[tot]=="NUM") num[tot]=read();
	}
	n=read();
	for(int i=1;i<=n;i++)
	{
		long long x;
		x=read();
		x=solve(x);
		if(x!=11111111)
			cout<<x<<endl;
	}
	return 0;
}

回复

0 条回复,欢迎继续交流。

正在加载回复...