社区讨论

0分求助~调了一下午

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

讨论操作

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

当前回复
0 条
当前快照
1 份
快照标识符
@mikcfy51
此快照首次捕获于
2025/11/29 21:45
3 个月前
此快照最后确认于
2025/12/01 16:40
3 个月前
查看原帖
CPP
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define endl '\n'
stack<int>num;
string s[2005];int n;int tot;
void oper(){
	int x;cin >> x;
	while(num.size())num.pop();
	num.push(x);
	for(int i = 1;i <= tot;i++){
		string opt = s[i].substr(0,3);
		if(opt == "NUM"){
			string tnum = s[i].substr(4);
			if(tnum.size() > 10){cout << "ERROR\n";return;}
			int nb = stoll(tnum);
			if(abs(nb) > 1e9){cout << "ERROR\n";return;}
			num.push(nb);
		}
		if(opt == "POP"){
			if(num.empty()){cout << "ERROR\n";return;}
			else num.pop();
		}
		if(opt == "INV"){
			if(num.empty()){cout << "ERROR\n";return;}
			else{int nb=num.top();num.pop();num.push(-nb);}
		}
		if(opt == "DUP"){
			if(num.empty()){cout << "ERROR\n";return;}
			else{int nb = num.top();num.push(nb);}
		}
		if(opt == "SWP"){
			if(num.size() < 2){cout << "ERROR\n";return;}
			else{
				int n1 = num.top();num.pop();
				int n2 = num.top();num.pop();
				num.push(n1);num.push(n2);
			}
		}
		if(opt == "ADD"){
			if(num.size() < 2){cout << "ERROR\n";return;}
			else{
				int n1 = num.top();num.pop();
				int n2 = num.top();num.pop();
				if(abs(n1+n2) > 1e9){cout << "ERROR\n";return;}
				num.push(n1+n2);
			}
		}
		if(opt == "SUB"){
			if(num.size() < 2){cout << "ERROR\n";return;}
			else{
				int n1 = num.top();num.pop();
				int n2 = num.top();num.pop();
				if(abs(n2-n1)>1e9){cout << "ERROR\n";return;}
				num.push(n2-n1);
			}
		}
		if(opt == "MUL"){
			if(num.size() < 2){cout << "ERROR\n";return;}
			else{
				int n1 = num.top();num.pop();
				int n2 = num.top();num.pop();
				if(abs(n1*n2) > 1e9){cout << "ERROR\n";return;}
				num.push(n1*n2);
			}
		}
		if(opt == "DIV"){
			if(num.size() < 2){cout << "ERROR\n";return;}
			else{
				int n1 = num.top();num.pop();
				int n2 = num.top();num.pop();
				if(n1 == 0){cout << "ERROR\n";return;}
				if(abs(n2/n1) > 1e9){cout << "ERROR\n";return;}
				num.push(n2/n1);
			}
		}
		if(opt == "MOD"){
			if(num.size() < 2){cout << "ERROR\n";return;}
			else{
				int n1 = num.top();num.pop();
				int n2 = num.top();num.pop();
				if(n1 == 0){cout << "ERROR\n";return;}
				if(abs(n2 % n1) > 1e9){cout << "ERROR\n";return;}
				num.push(n2 % n1);
			}
		}
	}
	if(num.size() != 1){cout << "ERROR\n";return;}
	cout << num.top() << "\n";
}
signed main(){
	while(getline(cin,s[++tot])){
		if(s[tot] == "END")break;
	}
	tot--;
	cin >> n;
	while(n--)oper();
	return 0;
}

回复

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

正在加载回复...