跳到正文

个人记录

7-25作业/重写ren_gao_zu

ren_gao_zu约 5 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 5 分钟

版本

  1. v1当前

作业

D4348 括弧匹配检验

C++
#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)

C++
#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 简单计算

C++
#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;
}
原文