开始: 2026-10-05 11:05:00

【集训03】CSP-J模拟赛1005

结束: 2026-10-06 00:00:00
当前  2026-11-04 10:33:58  类型: IOI  状态: 已经结束 


题解

#include <bits/stdc++.h>
using namespace std;
#define bywuting ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);

struct node {
	int type;
	int num;
};
string s;
int x[100100], n;
vector<node> ans, op, num;

int level(char c) {
	if (c == '+' || c == '-')
		return 1;
	if (c == '*' || c == '/')
		return 2;
	if (c == '(' || c == ')')
		return 0;
}

void change() {
	int tmp = 0, type;
	for (auto c : s) {
		if (c == 'x')
			tmp = 0, type = 1;
		else if (c >= '0' && c <= '9')
			tmp = tmp * 10 + (c - '0');
		else {
			if (tmp)
				ans.push_back({type, x[tmp]});
			ans.push_back({0, c});
			tmp = 0;
		}
	}
	if (tmp)
		ans.push_back({type, x[tmp]});
	for (auto to : ans)
		if (to.type)
			cout << to.num;
		else
			cout << char(to.num);
}

void first() {
	for (int i = ans.size() - 1; i >= 0; i--) {
		if (ans[i].type) {
			num.push_back(ans[i]);
		} else {
			if (char(ans[i].num) == ')')
				op.push_back(ans[i]);
			else if (char(ans[i].num) == '(') {
				while (char(op.back().num) != ')')
					num.push_back(op.back()), op.pop_back();
				op.pop_back();
			} else {
				while (op.size() && level(char(ans[i].num)) < level(char(op.back().num)))
					num.push_back(op.back()), op.pop_back();
				op.push_back(ans[i]);
			}
		}
	}
	while (op.size())
		num.push_back(op.back()), op.pop_back();
	bool f = 1;
	for (int i = num.size() - 1; i >= 0; i--) {
		node t = num[i];
		if (!f)
			cout << " ";
		if (t.type)
			cout << t.num;
		else
			cout << char(t.num);
		f = 0;
	}
	cout << "\n";
}

int main() {
	cin >> s >> n;
	for (int i = 1; i <= n; i++)
		cin >> x[i];
	change();
	cout << "\n";
	first();
	return 0;
}