模拟记-P2186 小 Z 的栈函数

Code_Fish_Hp / 2023-08-18 / 原文

哈哈哈哈哈哈哈

#include<bits/stdc++.h>
#define int long long
using namespace std;
const int MAXN=2005;
int a[MAXN],tot,n,t;
string s[MAXN];
stack<int>q;
inline bool ne(int x){
	return abs(x)>1000000000;
}
inline void error(){cout<<"ERROR"<<endl;}
inline void work(int x){
	q.push(x);
	for(int i=1;i<tot;i++){
		if(s[i]=="NUM"){
			if(ne(a[i])) return error();
			q.push(a[i]);
		}
		else if(s[i]=="POP"){
			if(q.empty()) return error();
			q.pop();
		}
		else if(s[i]=="INV"){
			if(q.empty()) return error();
			int k=-q.top();
			q.pop();
			q.push(k);
		}
		else if(s[i]=="DUP"){
			if(q.empty()) return error();
			int k=q.top();
			q.push(k);
		}
		else if(s[i]=="SWP"){
			if(q.size()<2) return error();
			int k=q.top();
			q.pop();
			int k1=q.top();
			q.pop();
			q.push(k);
			q.push(k1);
		}
		else if(s[i]=="ADD"){
			if(q.size()<2) return error();
			int k=q.top();
			q.pop();
			int k1=q.top();
			q.pop();
			if(ne(k+k1)) return error();
			q.push(k+k1);
		}
		else if(s[i]=="SUB"){
			if(q.size()<2) return error();
			int k=q.top();
			q.pop();
			int k1=q.top();
			q.pop();
			if(ne(k1-k)) return error();
			q.push(k1-k);
		}
		else if(s[i]=="MUL"){
			if(q.size()<2) return error();
			int k=q.top();
			q.pop();
			int k1=q.top();
			q.pop();
			if(ne(k1*k)) return error();
			q.push(k1*k);
		}
		else if(s[i]=="DIV"){
			if(q.size()<2) return error();
			int k=q.top();
			q.pop();
			int k1=q.top();
			q.pop();
			if(k==0) return error();
			if(ne(k1/k)) return error();
			q.push(k1/k);
		}
		else if(s[i]=="MOD"){
			if(q.size()<2) return error();
			int k=q.top();
			q.pop();
			int k1=q.top();
			q.pop();
			q.push(k1%k);
		}
		else error();
	}
	if(q.size()!=1) error();
	else cout<<q.top()<<endl;
}
signed main(){
	ios_base::sync_with_stdio(NULL);
	cin.tie(nullptr);
	cout.tie(nullptr);
	while(cin>>s[++tot]){
		if(s[tot]=="END") break;
		else if(s[tot]=="NUM") cin>>a[tot];
	}
	cin>>n;
	for(int i=1;i<=n;i++){
		cin>>t;
		work(t);
		while(!q.empty()) q.pop();
	}
	return 0;
}