1. 程式人生 > >Codeforces Round #525 (Div. 2) D. Ehab and another another xor problem 互動 二進位制 思維

Codeforces Round #525 (Div. 2) D. Ehab and another another xor problem 互動 二進位制 思維

題解

互動題
題目大意 有兩個數字a和b要你去猜 你可以詢問兩個數字c和d 系統會反饋給你a ^ c和b ^ d的大小比較結果 左邊大1右邊大-1相同0 最多猜62次

數值範圍小於2的30次方 說明最多有30個二進位制位 最開始使用一次確定a和b的大小關係 每個二進位制位使用兩次猜測 最後使用一次回答答案
從高到低遍歷二進位制位 之前的位被異或掉了當前位就是最高位 起著決定性的作用 考慮當前位的狀態 具體看備註

AC程式碼

#include <stdio.h>
#include <bits/stdc++.h>
using namespace std;
typedef long long ll; const int INF = 0x3f3f3f3f; int Ask(int a, int b) { printf("? %d %d\n", a, b); fflush(stdout); int res; scanf("%d", &res); return res; } int main() { #ifdef LOCAL //freopen("C:/input.txt", "r", stdin); #endif int a = 0, b = 0; bool Abig = Ask(0, 0) == 1; //a大 for (int i =
29; i >= 0; i--) //列舉二進位制位 前面的已經被異或掉 當前位為最高位起決定性作用 { int w = 1 << i; //當前位 int l = Ask(a | w, b); //a異或當前位後的結果 int r = Ask(a, b | w); //b if (l == 1 && r == -1) //如果a和b異或完都增大則當前位都為0 true; //本身就是0 else if (l == -1 && r == 1) //異或完了都變小則當前為都為1 a |= w, b |= w; //對應位置置為1 else //一個為1一個為0
{ if (Abig) //誰大誰為1 a |= w; else b |= w; Abig = l == 1; //相同時不變 只變不同 異或了一個之後一定相同 只需要判斷異或一個哪個大 } } printf("! %d %d\n", a, b); return 0; }