样例都对 但只有10分
查看原帖
样例都对 但只有10分
854995
flyWang楼主2023/10/15 15:43
#include<bits/stdc++.h>
#include<unordered_map>
#define endl '\n'
#define int int64_t
using namespace std;
string s,ptn,tmp;//ptn放最开始的模板
stack<char>stk;//存放符号
unordered_map<char, int>mp{{'^', 3}, { '*',2 }, { '/',2 }, { '+',1 }, { '-',1 }};
signed main() {
	cin >> s;
	int rec = 0;
	for (int i = 0; i < s.size(); ++i) {
		if (isdigit(s[i]))ptn += s[i];
		else {
			//^   */   +-
			if (s[i] == '^') {
				rec++;
				stk.push(s[i]);
			}
			else if (mp.find(s[i]) != mp.end()) {
				rec++;
				while (!stk.empty() && stk.top() != '(' && mp[s[i]] <= mp[stk.top()]) {
					ptn += stk.top();
					stk.pop();
				}
				stk.push(s[i]);
			}
			else if (s[i] == '(')stk.push(s[i]);
			else {
				while (stk.top() != '(') {
					ptn += stk.top();
					stk.pop();
				 }
				stk.pop();
			}
		}
	}
	while(!stk.empty()){ptn += stk.top();stk.pop();}
	for (int i = 0; i < ptn.size(); ++i) cout << ptn[i] << " ";
	cout << endl;
	//cout << rec << endl;
	
	stack<int>num;
	//把ptn当作一个栈,取 遇到符号就计算? 遇到^得继续往后找 其他的遇到就计算

	for (int k = 1; k < rec; ++k) {
		int tk = k; tmp = "";
		for (int i = 0; i < ptn.size(); ++i) {
			if (isdigit(ptn[i]))num.push(ptn[i] - '0');
			else {
				if (!tk) {
					while (!num.empty()) {
						string tt = to_string(num.top());tt += ' ';
						tmp.insert(0, tt);
						num.pop();
					}
					tmp += ptn.substr(i);
					break;
				}
				tk--;
				int last = num.top(); num.pop();
				int pre = num.top(); num.pop();
				if (ptn[i] == '^') pre = pow(pre, last);
				else if (ptn[i] == '*') pre = pre * last;
				else if (ptn[i] == '/') pre = pre / last;
				else if (ptn[i] == '+') pre = pre + last;
				else pre = pre - last;
				num.push(pre);
			}
		}
		//cout << "tmp = " << tmp <<"k = " << k  << endl;
		for (int m = 0; m < tmp.size() - 1;) {
			if (!isdigit(tmp[m])) { if (tmp[m] != ' ') { cout << tmp[m] << " "; }m++;}
			else {
				while (isdigit(tmp[m])) cout << tmp[m], m++;
				cout << " ";
			}
		}
		cout << tmp.back() << endl;
	}
	//if (num.empty()) cout << "Yes" << endl;
	//cout << tmp << endl;
	int pre = stoll(tmp); string start = to_string(pre);
	int last = stoll(tmp.substr(start.size()));
	char sign = tmp.back();
	if (sign == '^') pre = pow(pre, last);
	else if (sign == '*') pre = pre * last;
	else if (sign == '/') pre = pre / last;
	else if (sign == '+') pre = pre + last;
	else pre = pre - last;
	cout << pre << endl;
	return 0;
}
2023/10/15 15:43
加载中...