P7073题解
前言
本题作者的解法通过了全部测试数据,但不保证最坏情况下的时间复杂度。
题意简述
给定一个后缀逻辑表达式,其中有 个变量,初值已知。接下来给出 组独立的询问,每一组询问给出下标 ,表示若将第 个变量的值临时改为 ,表达式的值为多少。
题目分析
-
考虑简化问题,即先考虑没有询问时如何求表达式的值。该问题即为标准的算符优先法。
-
算符优先法
对于后缀表达式,维护一个运算数的栈。对字符流进行扫描:
- 每遇到一个运算数,就将其入栈。
- 每遇到一个运算符,就从栈顶弹出所需的操作数,再将运算后的结果入栈。
- 扫描结束后只剩下一个数,即为表达式最终的值。
-
再考虑运算
!的含义:将一个变量取反后,要么改变表达式的值,要么没有改变表达式的值。下文称为对答案有影响和没有影响。 -
由于
&和|存在短路,即 和 。 -
在计算过程中,一个值如果被短路,则所有这个值所涉及到的变量都对答案无影响。
-
考虑在算符优先法的过程中,在栈中压入一个结构体,其中包括值和计算出这个值的所有变量编号。
-
但由于直接对
vector进行操作过于昂贵,本人实现时改为存储vector的下标编号。 -
具体来说,类似并查集的思想,初始状态每个变量所对应
vector中只有自己的编号在计算过程中,每次进行二元运算时,暴力合并两个vector。如果有一个或两个可以被短路(有两个被短路是因为 或 时两个都可以被短路),就将对应vector中所有变量都设为对答案没有影响。 -
这里可以用一个小优化,即暴力合并
vector时,采用启发式策略,可以将合并部分复杂度降低至 。 -
但要注意整体复杂度并没有得到有效提升,因为将
vector中变量设为没有影响的过程最坏情况下依然为 。
关于复杂度
至此,本解法最坏情况下复杂度依然为 ,并且作者没有目前找到有效方法提升。
警示后人
数组大小要足够!
不够, 才够。
代码实现
部分代码有些重复,仅供参考。
代码
#include <iostream>
#include <cstring>
#include <vector>
#include <cassert>
using namespace std;
const int N = 1e6 + 10;
int a[N], val[N];
bool effective[N];
vector<int> ids[N];
int main() {
int n, q;
int len = 0;
string input;
while (cin >> input) {
if (isdigit(input[0])) {
n = stoi(input);
break;
}
if (input[0] == 'x') {
a[++len] = stoi(input.substr(1));
} else {
a[++len] = -input[0];
}
}
for (int i = 1; i <= n; i++) {
cin >> val[i];
ids[i].assign(1, i);
}
memset(effective, true, sizeof(effective));
vector<pair<int, int>> nums;
for (int i = 1; i <= len; i++) {
if (a[i] < 0) {
char op = -a[i];
assert(!nums.empty());
pair<int, int> x, y;
x = nums.back(); nums.pop_back();
if (op == '!') {
nums.push_back({!x.first, x.second});
continue;
}
assert(!nums.empty());
y = nums.back(); nums.pop_back();
if (op == '&' && x.first == 0) {
for (int j : ids[y.second]) {
effective[j] = false;
}
}
if (op == '&' && y.first == 0) {
for (int j : ids[x.second]) {
effective[j] = false;
}
}
if (op == '|' && x.first == 1) {
for (int j : ids[y.second]) {
effective[j] = false;
}
}
if (op == '|' && y.first == 1) {
for (int j : ids[x.second]) {
effective[j] = false;
}
}
int xlen = ids[x.second].size();
int ylen = ids[y.second].size();
if (xlen < ylen) {
swap(x, y);
}
for (int j : ids[y.second]) {
ids[x.second].push_back(j);
}
ids[y.second].clear();
int res = (op == '&' ? x.first & y.first : x.first | y.first);
nums.push_back({res, x.second});
} else {
nums.push_back({val[a[i]], a[i]});
}
}
cin >> q;
for (int _ = 0; _ < q; _++) {
int i;
cin >> i;
cout << (nums[0].first ^ effective[i]) << endl;
}
return 0;
}