警示后人
查看原帖
警示后人
997236
theb0t楼主2024/8/4 20:48

如果你像我这么写的,一定要注意,如果有个数他的计算结果ASCII码刚好是'+' '-'这样的字符,那你就错了,一定要加一个变量看看他是不是字符。

贴上WA代码

#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
int calc(char ch){
	if(ch=='+'||ch=='-') return 1;
	if(ch=='*'||ch=='/') return 2;
	if(ch=='^') return 3;
	if(ch=='(') return 4;
}
string fun(string s){
	stack<char> a,b;
	int len=s.size();
	for(int i=0;i<len;i++){
		char ch=s[i];
		if(ch>='0'&&ch<='9') b.push(ch);
		else if(ch==')'){
			while(a.top()!='('){
				b.push(a.top());
				a.pop();
			}
			a.pop();
		}
		else{
			k:;
			if(a.empty()||a.top()=='(') a.push(ch);
			else if(calc(ch)>calc(a.top())||(a.top()=='^'&&ch=='^')) a.push(ch);
			else{
				b.push(a.top());
				a.pop();
				goto k;
			}
		}
	} 
	while(!a.empty()){
		b.push(a.top());
		a.pop();
	}
	string res="";
	while(!b.empty()){
		res=(char)b.top()+res;
		b.pop();
	}
	return res;
}
ll calc_(ll a,ll b,char c){
	
	if(c=='+') return a+b;
	if(c=='-') return a-b;
	if(c=='*') return a*b;
	if(c=='/') return a/b;
	if(c=='^'){
//		cout<<"gg"<<a<<" "<<b<<endl;
		ll ans=1;
		for(int i=1;i<=b;i++) ans*=a;
//		cout<<ans<<endl;
		return ans;
	}
}
void Print(string s){
	vector<ll> v;
	for(int i=0;i<s.size();i++){
		if(s[i]=='+'||s[i]=='-'||s[i]=='*'||s[i]=='/'||s[i]=='^') v.push_back((ll)s[i]);
		else v.push_back(s[i]-'0');
	}
	for(int i=0;i<v.size();i++){
		if(v[i]=='+'||v[i]=='-'||v[i]=='*'||v[i]=='/'||v[i]=='^') cout<<(char)v[i];
		else cout<<v[i];
		cout<<" ";
	}
	cout<<endl;
	while(v.size()>1){
		int p=-1;
		for(int i=0;i<v.size();i++){
			if(v[i]=='+'||v[i]=='-'||v[i]=='*'||v[i]=='/'||v[i]=='^'){
				p=i;
				break;
			}
		}
		ll t1=v[p-2],t2=v[p-1];
		
		v[p]=calc_(t1,t2,(char)v[p]);
		v.erase(v.begin()+p-1);
		v.erase(v.begin()+p-2);
		for(int i=0;i<v.size();i++){
			if(v[i]=='+'||v[i]=='-'||v[i]=='*'||v[i]=='/'||v[i]=='^') cout<<(char)v[i];
			else cout<<v[i];
			cout<<" ";
		}
		cout<<endl;
	} 
}
int main(){
	ios::sync_with_stdio(false);
	cin.tie(0);
	string S;
	cin>>S;
	string s=fun(S);
//	cout<<s<<endl;
	Print(s);
	return 0;
}
2024/8/4 20:48
加载中...