#5RE求助(玄关)
查看原帖
#5RE求助(玄关)
1251425
Wxy13589159456楼主2024/10/27 16:43
#include<bits/stdc++.h>
using namespace std;
int str[31],t;
int l[31],r[31];
bool flag[31];
int build(int lsize,int rsize)
{
	int p=0,p1=0,p2=0,p3=0;
	if(lsize>=rsize)return lsize;
	for(int i=lsize;i<=rsize;i++)
	{
		if(str[i]=='(')p++;
		if(str[i]==')')p--;
		if(flag[i]==0)
		{
			//cout<<p<<' ';
			if(p==0 && (str[i]=='+' || str[i]=='-'))p1=i;
			if(p==0 && (str[i]=='*' || str[i]=='/'))p2=i;
			if(p==0 && str[i]=='^')p3=i;
		}
	}
	//cout<<'\n';
	if(p2==0)p2=p3;
	if(p1==0)p1=p2;
	if(p1==0)return build(lsize+1,rsize-1);
	l[p1]=build(lsize,p1-1);
	r[p1]=build(p1+1,rsize);
	return p1;
}
long long dfs(int root)
{
	long long L,R;
	if(flag[root])return str[root];
	L=dfs(l[root]);
	R=dfs(r[root]);
	if(str[root]=='^')return pow(L,R);
	if(str[root]=='+')return L+R;
	if(str[root]=='-')return L-R;
	if(str[root]=='*')return L*R;
	if(str[root]=='/')return L/R;
	return 0;
}
int main()
{
	char ch;
	while(ch!='\n' && (ch=getchar())!='\n')
	{
		if(ch<='9' && ch>='0')
		{
			flag[++t]=true;
			int a=ch-'0';
			while((ch=getchar())<='9' && ch>='0' && ch!='\n')
				a=a*10+(ch-'0');
			str[t]=a;
			if(!(ch<='9' && ch>='0') && ch!='\n')str[++t]=ch;
		}
		else str[++t]=ch;
	}
	cout<<dfs(build(1,t));
	return 0;
}
2024/10/27 16:43
加载中...