其实题目中的 是唬人的,我们只需要将所有串的答案求出来就行了。
按照题目中给出的提示,我们可以对每个串记录三个答案串 , 和 ,分别表示 的答案串对应题目中所述的 、 和 型串时,最优的答案串。
在解释如何转移之前,我们先看看比较原则:对于答案串 和 ,如果 是更优的,它必然满足:
- 若 与 长度不相等,那么 长度必然更短;
- 否则, 的字典序更小。
注意,这与普通的字符串比大小是不一样的。
现在我们可以按照题目中的语法规则进行转移了。这将分为几种情况。
型串可以:
- “或”上一个 型串变成 型串,即 ;
- 左右加上括号变成 型串,即 。
型串可以:
- “与”上一个 型串变成 型串,即 ;
- 本身可以变为 型串,即 。
型串可以:
- “非”上自己变成 型串,即 ;
- 本身可以变为 型串,即 。
按照规则转移即可。
需要注意的是,当进行与、或运算时,两端答案串可以换位置。
转移起点:,,。
至于转移顺序,我们可以将转移抽象成一个图,用最短路算法的思想,用优先队列贪心取出每次更新别人的值即可。
#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;
}