题解:[CSP-J 2020] 表达式

· · 题解

P7073题解

前言

本题作者的解法通过了全部测试数据,但不保证最坏情况下的时间复杂度。

题意简述

给定一个后缀逻辑表达式,其中有 n 个变量,初值已知。接下来给出 q 组独立的询问,每一组询问给出下标 i ,表示若将第 i 个变量的值临时改为 i ,表达式的值为多少。

题目分析

::::warning[关于复杂度] 至此,本解法最坏情况下复杂度依然为 O(n^2) ,并且作者没有目前找到有效方法提升。 ::::

::::warning[警示后人] 数组大小要足够!

:::: --- ## 代码实现 部分代码有些重复,仅供参考。 ::::success[代码] ```cpp #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; } ``` :::: ---