题解:CF913E Logical Expression

· · 题解

其实题目中的 n 是唬人的,我们只需要将所有串的答案求出来就行了。

按照题目中给出的提示,我们可以对每个串记录三个答案串 E_x,T_x 和 F_x,分别表示 x 的答案串对应题目中所述的 E、T 和 F 型串时,最优的答案串。

在解释如何转移之前,我们先看看比较原则:对于答案串 S 和 T,如果 S 是更优的,它必然满足:

注意,这与普通的字符串比大小是不一样的。

现在我们可以按照题目中的语法规则进行转移了。这将分为几种情况。

+ “或”上一个 $T$ 型串变成 $E$ 型串,即 $E_x|T_y\to E_{x|y}$; + 左右加上括号变成 $F$ 型串,即 $(E_x)\to F_x$。 $T$ 型串可以: + “与”上一个 $F$ 型串变成 $T$ 型串,即 $T_x\&F_y\to T_{x\&y}$; + 本身可以变为 $E$ 型串,即 $T_x\to E_x$。 $F$ 型串可以: + “非”上自己变成 $F$ 型串,即 $!F_x\to F_{255-x}$; + 本身可以变为 $T$ 型串,即 $F_x\to T_x$。 按照规则转移即可。 需要注意的是,当进行与、或运算时,两端答案串可以换位置。 转移起点:$F_{15}="x"$,$F_{51}="y"$,$F_{85}="z"$。 至于转移顺序,我们可以将转移抽象成一个图,用最短路算法的思想,用优先队列贪心取出每次更新别人的值即可。 ```cpp #include <bits/stdc++.h> using namespace std; bool comp(string s, string t) { // 是否 s > t if (s.size() != t.size()) return s.size() > t.size(); return s > t; } struct node { int o, x; string s; bool operator < (const node &a) const { return comp(s, a.s); } }; priority_queue <node> q; string s[4][256]; bool vis[4][256]; string combine(string s, string t, char c) { // 与或运算 string A = s + c + t, B = t + c + s; return A < B ? A : B; } void init() { // 1 对应 E 串,2 对应 T 串,3 对应 F 串 for (int i = 1; i <= 3; i++) for (int j = 0; j < 256; j++) { int T = 1000; while (T--) s[i][j] += '#'; // 初始化无穷大 } s[3][15] = "x"; q.push({3, 15, "x"}); s[3][51] = "y"; q.push({3, 51, "y"}); s[3][85] = "z"; q.push({3, 85, "z"}); while (!q.empty()) { node t = q.top(); q.pop(); if (vis[t.o][t.x]) continue; vis[t.o][t.x] = 1; string T1 = s[t.o][t.x]; if (t.o == 1) { if (comp(s[3][t.x], '(' + T1 + ')')) s[3][t.x] = '(' + T1 + ')', q.push({3, t.x, s[3][t.x]}); for (int i = 0; i < 256; i++) { string T2 = s[2][i]; if (comp(s[1][t.x | i], combine(T1, T2, '|'))) s[1][t.x | i] = combine(T1, T2, '|'), q.push({1, t.x | i, s[1][t.x | i]}); } } else if (t.o == 2) { if (comp(s[1][t.x], T1)) s[1][t.x] = T1, q.push({1, t.x, s[1][t.x]}); for (int i = 0; i < 256; i++) { string T2 = s[3][i]; if (comp(s[2][t.x & i], combine(T1, T2, '&'))) s[2][t.x & i] = combine(T1, T2, '&'), q.push({2, t.x & i, s[2][t.x & i]}); } } else { if (comp(s[2][t.x], T1)) s[2][t.x] = T1, q.push({2, t.x, s[2][t.x]}); if (comp(s[3][255 - t.x], '!' + T1)) s[3][255 - t.x] = '!' + T1, q.push({3, 255 - t.x, s[3][255 - t.x]}); } } for (int i = 0; i < 256; i++) { // 求最优串 if (!comp(s[1][i], s[2][i]) && !comp(s[1][i], s[3][i])) s[0][i] = s[1][i]; if (!comp(s[2][i], s[1][i]) && !comp(s[2][i], s[3][i])) s[0][i] = s[2][i]; if (!comp(s[3][i], s[1][i]) && !comp(s[3][i], s[2][i])) s[0][i] = s[3][i]; } } int main() { init(); int _; scanf("%d", &_); while (_--) { int x = 0; char c = getchar(); while (!isdigit(c)) c = getchar(); while (isdigit(c)) x = x << 1 | c - '0', c = getchar(); cout << s[0][x] << '\n'; } return 0; } ```