【题目链接】
【思路要点】
- 首先,我们可以通过 2 2 2 次操作确定第一个字符,不妨令其为 A A A 。
- 接下来,对于 2 ≤ i ≤ N − 1 2≤i≤N-1 2≤i≤N−1 若我们已经确定了前 i − 1 i-1 i−1 个字符为 S S S ,我们询问 S B S X B S X X S X Y SBSXBSXXSXY SBSXBSXXSXY ,若得到的结果为 i − 1 i-1 i−1 ,则说明第 i i i 个字符为 Y Y Y ,若得到的结果为 i i i ,则说明第 i i i 个字符为 B B B ,否则,说明第 i i i 个字符为 X X X 。
- 再用 2 2 2 次操作确定最后一个字符即可。
- 时间复杂度 O ( N 2 ) O(N^2) O(N2) ,交互次数不超过 N + 2 N+2 N+2。
【代码】
#include "combo.h" #include<bits/stdc++.h> using namespace std; const char c[4] = {'A', 'B', 'X', 'Y'}; string guess_sequence(int n) { char first; if (press("AB")) { if (press("A")) first = 'A'; else first = 'B'; } else { if (press("X")) first = 'X'; else first = 'Y'; } string ans = ""; ans += first; if (n == 1) return ans; int tot = 0; char a[4] = {0, 0, 0, 0}; for (int i = 0; i <= 3; i++) if (c[i] != first) a[++tot] = c[i]; else a[0] = c[i]; for (int i = 2; i <= n - 1; i++) { string tmp = ""; tmp += ans, tmp += a[1]; for (int j = i + 1; j <= n; j++) tmp += a[0]; for (int k = 1; k <= 3; k++) { tmp += ans, tmp += a[2], tmp += a[k]; for (int j = i + 2; j <= n; j++) tmp += a[0]; } int tans = press(tmp); if (tans == i) ans += a[1]; else if (tans == i + 1) ans += a[2]; else ans += a[3]; } if (press(ans + a[1]) == n) ans += a[1]; else if (press(ans + a[2]) == n) ans += a[2]; else ans += a[3]; return ans; }