需要样例提供
查看原帖
需要样例提供
1526749
linda_xhy楼主2024/11/28 20:53

能提供一组样例吗?五个点全WA但是我测试了很多次答案都没有问题

#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
using namespace std;
const int MAXN = 50;
int n;
int top;
int v[MAXN]; // v为操作数栈,c为运算符栈 
char s[MAXN], c[MAXN]; 
void Push(int x, int flag) { // 入栈
	if (!flag) c[++top] = x; // flag=0表示运算符 
	else v[top] = x; // flag=1表示操作数 
} 
int Pow(int x, int n) { // 乘方运算 
	int sum = 1;
	for (int i = 1; i <= n; i++) sum *= x;
	return sum;
}
void Pop() {
	if (c[top] == '+') v[top - 1] += v[top];
	if (c[top] == '-') v[top - 1] -= v[top];
	if (c[top] == '*') v[top - 1] *= v[top];
	if (c[top] == '/') v[top - 1] /= v[top];
	if (c[top] == '^') v[top - 1] = Pow(v[top - 1], v[top]);
	--top;
}
int Opr(char x) {
	if (x == '+' || x == '-') return 0;
	if (x == '*' || x == '/') return 1;
	if (x == '^') return 2;
	return -1;
} 
bool Check(char x) {
	if (Opr(x) <= Opr(c[top])) return true;
	return false;
}
int main() {
	scanf("%s", s);
	n = strlen(s);
	s[n] = ')'; // 手动加了一个)作为结尾 
	Push('(', 0); // 手动把一个(放在了栈中 
	for (int i = 0; i <= n; i++) { // 手写栈 
		while (s[i] == '(') Push(s[i++], 0);
		int x = 0;
		while (isdigit(s[i])) x = x * 10 + s[i++] - '0';
		Push(x, 1);
		while (true) {
			if (s[i] == ')') {
				while (c[top] != '(') Pop();
				//cout << v[top] << "在这里" << endl;
				v[top-1] = v[top--];
				//cout << v[top-1] << "变到这里" << endl;
			} else {
				while (Check(s[i])) Pop();
				Push(s[i], 0);
				break;
			}
			++i;
			if (i > n) break;
		}
	}
	printf("%d", v[0]);
	return 0; 
}
2024/11/28 20:53
加载中...