求中缀表达式的值 蒟蒻求助为什么运行错误
  • 板块学术版
  • 楼主Lorcna
  • 当前回复1
  • 已保存回复1
  • 发布时间2021/8/12 10:18
  • 上次更新2023/11/4 10:57:22
查看原帖
求中缀表达式的值 蒟蒻求助为什么运行错误
78359
Lorcna楼主2021/8/12 10:18
#include<bits/stdc++.h>
using namespace std;
int n,m;
stack<int> s1;
stack<char> s2;
char sr[1000000];
int sum[1000000];
int lev(char a)
{
	if(a=='+'||a=='-') return 1;
	if(a=='*'||a=='/') return 2;
	if(a=='^') return 3;
	return 0;
}

void js(stack<int> &s1,stack<char> &s2)
{
  int y=s1.top();
	s1.pop();
	int x=s1.top();
	s1.pop();
	char z=s2.top();
	s2.pop();
	if(z=='+') s1.push(x+y);
	if(z=='-') s1.push(x-y);
	if(z=='*') s1.push(x*y);
	if(z=='/') s1.push(x/y);
	if(z=='^') s1.push(pow(x,y));	
}
int c(int x)
{
	return x!=0;
}

int main()
{
  scanf("%s",sr+1);
  n=strlen(sr+1)-1;
  for(int i=1;i<=n;i++)
  {
  	sum[i]+=sum[i-1];
  	if(sr[i]=='(') sum[i]++;
  	if(sr[i]==')') sum[i]--;
	}
	bool out=false;
	for(int i=2;i<=n;i++)
	{
		if(c(lev(sr[i]))&&c(lev(sr[i-1]))) 
		{
		  out=true; 
			break;
		}
		if(n==1&&c(lev(sr[1]))||sum[n]||out)
		{
			printf("NO");
			return 0;
		}
	}
	int tmp=0;
	bool flag=false;
	for(int i=1;i<=n;++i)
  {
  	if('0'<=sr[i]&&sr[i]<='9')
  	{
  		tmp=(tmp<<3)+(tmp<<1)+sr[i]-'0';
  		flag=true;
		}
		else{
			if(flag) {s1.push(tmp); tmp=0; flag=false;}
			if(sr[i]=='(') {s2.push(sr[i]); continue;}
			if(sr[i]==')') 
			{
				while(s2.top()!='(') js(s1,s2);
				s2.pop();
				continue;
			}
		  while(!s2.empty()&&lev(s2.top())>=lev(sr[i]))
		    js(s1,s2);
		  s2.push(sr[i]);
		}
	}
	if(flag) 
	{
	  s1.push(tmp);
	  tmp=0;
	  flag=false;
	}
	while(!s2.empty()) js(s1,s2);
	printf("%d",s1.top());
	return 0;
}
2021/8/12 10:18
加载中...