跳到正文

算法·理论

神秘的前中后缀表达式互相转换/求值

litjohn约 17 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 17 分钟

版本

  1. v1当前

表达式转换

经典的算法是建出抽象语法树,然后前序遍历就是前缀,中序遍历是中缀,后序遍历就是后缀。时间复杂度 O(n2)O(n^2)(中缀转前后缀)或 O(n)O(n)(前后缀互相转化)。

只含 + - * / 四个运算符及 ( ) 且所有数字均在 int 范围内的模板:

中转前

C++
#include <bits/stdc++.h>

using namespace std;
basic_string<char> s;
array<int, 1005> a;

struct node {
	char opt;
	int num;
	node *l, *r;

	node(char ch) : num(114514), opt(ch), l(nullptr), r(nullptr) {}
	node(int x) : num(x), opt(0), l(nullptr), r(nullptr) {}
} *rt {nullptr};

void build(int l, int r, node *&p) {
	if (s[l] == '(' && s[r] == ')') {
		build(l + 1, r - 1, p);
	} else {
		basic_string<char> tmp = s.substr(l, r - l + 1);

		if (all_of(tmp.begin(), tmp.end(), [](char x) -> bool {return isdigit(x);})) {
			p = new node(stoi(tmp));
		} else {
			int pos = 0, min_ord = 3000;
			for (int i = l; i <= r; ++i) {
				if (a[i] < min_ord || (a[i] < 2000 && a[i] == min_ord)) {
					pos = i;
					min_ord = a[i];
				}
			}

			p = new node(s[pos]);

			if (l < pos) {
				build(l, pos - 1, p->l);
			}

			if (r > pos) {
				build(pos + 1, r, p->r);
			}

		}
	}
}

void firstord(node *p) {
	if (p) {
		if (p->num != 114514) {
			cout << p->num << " ";
		} else {
			cout << p->opt << " ";
		}
		firstord(p->l);
		firstord(p->r);
	}
}

int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(nullptr);
	cin >> s;

	int cnt = 0;
	for (int i = 0; i < s.size(); ++i) {
		if (s[i] == '+' || s[i] == '-') {
			a[i] = 1;
		} else if (s[i] == '*' || s[i] == '/') {
			a[i] = 2;
		} else if (isdigit(s[i])) {
			a[i] = 2000;
		} else if (s[i] == '(') {
			a[i] = 2000;
			cnt++;
		} else if (s[i] == ')') {
			a[i] = 2000;
			cnt--;
		}

		a[i] += 3 * cnt;
	}

	for (int i = s.size() - 1; i >= 0; --i) {
		if (s[i] == '(' || s[i] == ')') {
			s.erase(s.begin() + i);
			for (int j = i; j < s.size(); ++j) {
				a[j] = a[j + 1];
			}
		}
	}

	build(0, s.size() - 1, rt);
	firstord(rt);
	return 0;
}

中转后

C++
#include <bits/stdc++.h>

using namespace std;
basic_string<char> s;
array<int, 1005> a;

struct node {
	char opt;
	int num;
	node *l, *r;

	node(char ch) : num(114514), opt(ch), l(nullptr), r(nullptr) {}
	node(int x) : num(x), opt(0), l(nullptr), r(nullptr) {}
} *rt {nullptr};

void build(int l, int r, node *&p) {
	if (s[l] == '(' && s[r] == ')') {
		build(l + 1, r - 1, p);
	} else {
		basic_string<char> tmp = s.substr(l, r - l + 1);

		if (all_of(tmp.begin(), tmp.end(), [](char x) -> bool {return isdigit(x);})) {
			p = new node(stoi(tmp));
		} else {
			int pos = 0, min_ord = 3000;
			for (int i = l; i <= r; ++i) {
				if (a[i] < min_ord || (a[i] < 2000 && a[i] == min_ord)) {
					pos = i;
					min_ord = a[i];
				}
			}

			p = new node(s[pos]);

			if (l < pos) {
				build(l, pos - 1, p->l);
			}

			if (r > pos) {
				build(pos + 1, r, p->r);
			}

		}
	}
}

void postOrder_travel(node *p) {
	if (p) {
		postOrder_travel(p->l);
		postOrder_travel(p->r);
		if (p->num != 114514) {
			cout << p->num << " ";
		} else {
			cout << p->opt << " ";
		}
	}
}

int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(nullptr);
	cin >> s;

	int cnt = 0;
	for (int i = 0; i < s.size(); ++i) {
		if (s[i] == '+' || s[i] == '-') {
			a[i] = 1;
		} else if (s[i] == '*' || s[i] == '/') {
			a[i] = 2;
		} else if (isdigit(s[i])) {
			a[i] = 2000;
		} else if (s[i] == '(') {
			a[i] = 2000;
			cnt++;
		} else if (s[i] == ')') {
			a[i] = 2000;
			cnt--;
		}

		a[i] += 3 * cnt;
	}

	for (int i = s.size() - 1; i >= 0; --i) {
		if (s[i] == '(' || s[i] == ')') {
			s.erase(s.begin() + i);
			for (int j = i; j < s.size(); ++j) {
				a[j] = a[j + 1];
			}
		}
	}

	build(0, s.size() - 1, rt);
	postOrder_travel(rt);
	return 0;
}

注意到数字一定是表达式树的叶子结点且表达式树的叶子结点必定是数字。表达式树的前序遍历必定以一串操作符开始,以一串数字结尾。后续遍历反之。这方便了我们判断前缀/后缀的不同子树在字符串表示中的起止位置。

前转后

后转前

表达式求值

建个表达式树然后随便乱做就行了。

中缀表达式求值

C++
#include <bits/stdc++.h>

using namespace std;
constexpr long long mod = 1e9 + 7;
basic_string<char> s;
array<int, 1005> a;

struct node {
    char opt;
    int num;
    long long val;
    node *l, *r;

    explicit node(char ch) : num(114514), opt(ch), l(nullptr), r(nullptr) {}

    explicit node(int x) : num(x), opt(0), l(nullptr), r(nullptr) {}
} *rt{nullptr};

void build(int l, int r, node *&p) {
    basic_string<char> tmp = s.substr(l, r - l + 1);

    if (all_of(tmp.begin(), tmp.end(), [](char x) -> bool { return isdigit(x); })) {
        p = new node(stoi(tmp));
    } else {
        int pos = 0, min_ord = 3000;
        for (int i = l; i <= r; ++i) {
            if (a[i] < min_ord || (a[i] < 2000 && a[i] == min_ord)) {
                pos = i;
                min_ord = a[i];
            }
        }

        p = new node(s[pos]);

        if (l < pos) {
            build(l, pos - 1, p->l);
        }

        if (r > pos) {
            build(pos + 1, r, p->r);
        }
    }
}

void calc(node *const p) {
    if (p) {
        if (p->opt) {
            calc(p->l);
            calc(p->r);

            if (p->opt == '+') {
                p->val = (p->l->val + p->r->val) % mod;
            } else if (p->opt == '-') {
                p->val = (p->l->val - p->r->val) % mod;
            } else if (p->opt == '*') {
                p->val = (p->l->val * p->r->val) % mod;
            } else {
                p->val = (p->l->val / p->r->val) % mod;
            }
        } else {
            p->val = p->num;
        }
    }
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cin >> s;

    int cnt = 0;
    for (int i = 0; i < s.size(); ++i) {
        if (s[i] == '+' || s[i] == '-') {
            a[i] = 1;
        } else if (s[i] == '*' || s[i] == '/') {
            a[i] = 2;
        } else if (isdigit(s[i])) {
            a[i] = 2000;
        } else if (s[i] == '(') {
            a[i] = 2000;
            cnt++;
        } else if (s[i] == ')') {
            a[i] = 2000;
            cnt--;
        }

        a[i] += 3 * cnt;
    }

    for (int i = s.size() - 1; i >= 0; --i) {
        if (s[i] == '(' || s[i] == ')') {
            s.erase(s.begin() + i);
            for (int j = i; j < s.size(); ++j) {
                a[j] = a[j + 1];
            }
        }
    }

    build(0, s.size() - 1, rt);
    calc(rt);
    cout << (rt->val + mod) % mod;
    return 0;
}

后缀表达式求值

洛谷有模板,用栈乱搞就行。

当然,也可以建表达式树。

放一个用栈乱搞的代码。

C++
#include <bits/stdc++.h>

using namespace std;
constexpr long long mod = 1e9 + 7;
basic_string<char> s;

struct node {
	long long num;
	char opt;

	node(long long n) : num(n), opt(0) {}
	node(char ch) : opt(ch), num(2e9) {}
};
vector<node> expression;
stack<node, vector<node>> tmp;

int main() {
	getline(cin, s);

	long long x = -1;
	for (auto i : s) {
		if (i == ' ') {
			if (x != -1) {
				expression.emplace_back(x);
				x = -1;
			}
		} else if (isdigit(i)) {
			if (x == -1) {
				x = i - '0';
			} else {
				x = x * 10 + i - '0';
				x %= mod;
			}
		} else {
			expression.emplace_back(i);
		}
	}

	for (auto i: expression) {
		if (i.opt != 0) {
			node y = tmp.top();
			tmp.pop();
			node x = tmp.top();
			tmp.pop();

			if (i.opt == '+') {
				tmp.emplace((x.num + y.num) % mod);
			} else if (i.opt == '-') {
				tmp.emplace((x.num - y.num) % mod);
			} else if (i.opt == '*') {
				tmp.emplace((x.num * y.num) % mod);
			} else if (i.opt == '/') {
				tmp.emplace((x.num / y.num) % mod);
			}
		} else {
			tmp.push(i);
		}
	}

	cout << (tmp.top().num + mod) % mod;
	return 0;
}

前缀表达式求值

和后缀大同小异。

C++
#include <bits/stdc++.h>

using namespace std;
constexpr long long mod = 1e9 + 7;
basic_string<char> s;

struct node {
	long long num;
	char opt;

	node(long long n) : num(n), opt(0) {}
	node(char ch) : opt(ch), num(2e9) {}
};
vector<node> expression;
stack<node, vector<node>> tmp;

int main() {
	getline(cin, s);
	s.push_back(' ');

	long long x = -1;
	for (auto i : s) {
		if (i == ' ') {
			if (x != -1) {
				expression.emplace_back(x);
				x = -1;
			}
		} else if (isdigit(i)) {
			if (x == -1) {
				x = i - '0';
			} else {
				x = x * 10 + i - '0';
				x %= mod;
			}
		} else {
			expression.emplace_back(i);
		}
	}

//	for (auto i: expression) {
//		if (i.opt) {
//			cout << i.opt << " ";
//		} else {
//			cout << i.num << " ";
//		}
//	}

	for (int pos = expression.size() - 1; pos >= 0; --pos) {
		const node i = expression[pos];
		if (i.opt != 0) {
			node x = tmp.top();
			tmp.pop();
			node y = tmp.top();
			tmp.pop();

			if (i.opt == '+') {
				tmp.emplace((x.num + y.num) % mod);
			} else if (i.opt == '-') {
				tmp.emplace((x.num - y.num) % mod);
			} else if (i.opt == '*') {
				tmp.emplace((x.num * y.num) % mod);
			} else if (i.opt == '/') {
				tmp.emplace((x.num / y.num) % mod);
			}
		} else {
			tmp.push(i);
		}
	}

	cout << (tmp.top().num + mod) % mod;
	return 0;
}
原文