专栏文章

7-25作业/重写ren_gao_zu

个人记录参与者 1已保存评论 0

文章操作

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

当前评论
0 条
当前快照
1 份
快照标识符
@mioq9jto
此快照首次捕获于
2025/12/02 23:23
3 个月前
此快照最后确认于
2025/12/02 23:23
3 个月前
查看原文

作业

D4348 括弧匹配检验

CPP
#include<bits/stdc++.h>
#define int long long
using namespace std;
string s;
stack<char>t;
signed main(){
	cin>>s;
	for(int i=0;i<s.size();i++){
		if(s[i]=='('||s[i]=='['){
			t.push(s[i]);
		}
		if(s[i]==')'){
			if(t.size()==0||t.top()!='('){
				cout<<"Wrong";
				return 0;
			}
			else{
				t.pop();
			}
			
		}
		if(s[i]==']'){
			if(t.size()==0||t.top()!='['){
				cout<<"Wrong";
				return 0;
			}
			else t.pop();
		}
	}
	if(!t.size())cout<<"OK";
	else cout<<"Wrong";
	return 0;
}

D4350 计算(calc)

CPP
#include<bits/stdc++.h>
#define int long long
using namespace std;
string s;
stack<int>num;
stack<char>op;
int nb=0;
int yxj(char c){
	if(c=='^')return 3;
	if(c=='*'||c=='/')return 2;
	if(c=='+'||c=='-')return 1;
	if(c=='(')return 0;
}
void yun(){
	int y=num.top();
	num.pop();
	int x=num.top();
	num.pop();
	char f=op.top();
	op.pop();
	if(f=='+')num.push(x+y);
	if(f=='-')num.push(x-y) ;
	if(f=='*')num.push(x*y) ;
	if(f=='/')num.push(x/y) ;
	if(f=='^')num.push(pow(x,y));
}
signed main(){
	cin>>s;
	for(int i=0;i<s.size();i++){
		if(s[i]>='0'&&s[i]<='9'){
			nb=nb*10+s[i]-'0';
		}
		else{
			if(s[i]=='(')op.push(s[i]);
			if(s[i-1]<='9'&&s[i-1]>='0'){
				num.push(nb);
				nb=0;
			}
			if(s[i]==')'){
				while(op.top()!='(')yun();
				op.pop();
			}
			if(s[i]=='+'||s[i]=='-'||s[i]=='*'||s[i]=='/'||s[i]=='^'){
				while(!op.empty()&&yxj(op.top())>=yxj(s[i]))yun();
				op.push(s[i]);
			}
				
		}
	}
	int l=s.size()-1;
	if(s[l]>='0'&&s[l]<='9')num.push(nb);
	while(op.size()){
		yun();
	}cout<<num.top();
	return 0;
}

重写

D20011 简单计算

CPP
#include<bits/stdc++.h>
#define int long long
using namespace std;
string s;
stack<int>num;
stack<char>op;
int nb=0;
int yxj(char c){
	if(c=='^')return 3;
	if(c=='*'||c=='/')return 2;
	if(c=='+'||c=='-')return 1;
}
void suan(){
	int x=num.top();
	num.pop();
	int y=num.top();
	num.pop();
	char f=op.top();
	op.pop();
	if(f=='+')num.push(x+y);
	if(f=='-')num.push(y-x) ;
	if(f=='*')num.push(x*y) ;
	if(f=='/')num.push(y/x) ;
	if(f=='^')num.push(pow(y,x)) ;
}
signed main(){
	cin>>s;
	for(int i=0;i<s.size();i++){
		if(s[i]>='0'&&s[i]<='9'){
			nb=nb*10+s[i]-'0';
		}
		else{
			num.push(nb);
			nb=0;
			while(op.size()&&yxj(op.top())>=yxj(s[i]))suan();
			op.push(s[i]);
		}
	}
	num.push(nb);
	while(op.size()){
		suan();
	}cout<<num.top();
	return 0;
}

评论

0 条评论,欢迎与作者交流。

正在加载评论...