求调,样例过不去
查看原帖
求调,样例过不去
488395
Proxima_Centauri楼主2023/8/23 13:21

rt。 solve把中缀转成后缀,dfs遍历后缀,最后主函数来模拟,outp输出。 跪谢各位大佬。

#include <iostream>
#include <cstdio>
#include <string>
#include <cmath>
#include <algorithm>
#include <stack>
using namespace std;
string st;
int cnt, n, id, top, tot;
int num[110], s[110], pd[110], lf[110], rt[110], d[110];
char op[110];
stack<int> sta;
void solve(int x, int l, int r)
{
	if (l == r)
	{
		num[x] = st[l] - '0';
		return;
	}
	int p = -1, q = -1, t = -1;
	for (int i = l; i <= r; i++)
	{
		if (st[i] == '(') i = pd[i];
		if (st[i] == '+' || st[i] == '-') p = i;
		if (st[i] == '*' || st[i] == '/') q = i;
		if (st[i] == '^' && t == -1) t = i;
	}
	if (p == -1) p = q;
	if (p == -1) p = t;
	if (p == -1) solve(x, l + 1, r - 1);
	else
	{
		op[x] = st[p];
		lf[x] = ++cnt;
		solve(lf[x], l, p - 1);
		rt[x] = ++cnt;
		solve(rt[x], p + 1, r);
	}
}
void dfs(int x)
{
	if (x == 0) return;
	dfs(lf[x]);
	dfs(rt[x]);
	d[++tot] = x;
}
void outp(int y)
{
	for (int i = 1; i <= top; i++) cout << s[i] << " ";
	for (int i = y; i <= tot; i++)
		if (!lf[i]) cout << num[d[i]] << " ";
		else cout << op[d[i]] << " ";
	cout << endl;
}
int main()
{
	cin >> st;
	n = st.size();
	st = ' ' + st;
	for (int i = 1; i <= n; i++)
	{
		if (st[i] == '(') sta.push(i);
		if (st[i] == ')')
		{
			pd[sta.top()] = i;
			sta.pop();
		}
	}
	int root = ++cnt;
	solve(root, 1, n);
	dfs(root);
	outp(1);
	for (int i = 1; i <= tot; i++)
	{
		if (!lf[i]) s[++top] = num[d[i]];
		else 
		{
			int b = s[top--];
			int a = s[top--];
			if (op[d[i]] == '+') s[++top] = a + b;
			else if (op[d[i]] == '-') s[++top] = a - b;
			else if (op[d[i]] == '*') s[++top] = a * b;
			else if (op[d[i]] == '/') s[++top] = a / b;
			else s[++top] = pow(a, b);
			outp(i + 1);
		}
	}
	return 0;
}
2023/8/23 13:21
加载中...