跳到正文

个人记录

题解:CF1780D Bit Guessing Game

zhangxinyijdfz约 3 分钟
原文
文章信息与版本

文章信息

发布
2026年8月17日
收录
2026年8月17日
更新
2026年11月18日
篇幅
约 3 分钟
获赞
1

版本

  1. v2当前
  2. v1

题目大意

KiraKira 想一个数 nn ,告诉你它二进制中 11 的个数( popcountpopcount )。你最多减 3030 次数,每次 KiraKira 返回新数的 popcountpopcount 。你要通过这些变化反推出原始 nn,最后 !! nn 提交答案获胜。

思路

定义变量 ansans , opop , xx , nowcntnowcnt , lastcntlastcnt 。

变量名含义
ansans答案
opop最后一位 11 的位置
xx2op−1+12^{op}-1+1
nowcntnowcnt现在 11 的个数
lastcntlastcnt减去 xx 前 11 的个数

每进行一轮, ans+=xans+=x , op=nowcnt+1−lastcntop=nowcnt+1-lastcnt ( 因为二进制从 00 开算,所以 opop 应该等于变化量) , x=2op−1+1x=2^{op}-1+1 , nowcntnowcnt 用 −x-x 查,再减去 opop (减后增长的 11 的数量), lastcntlastcnt 继承上一轮 nowcntnowcnt 。

当 nowcnt=0nowcnt=0 时, nn 原本的 11 已经全部删过一遍,于是 nn 变成了此时的 opop 个 11 ,则 ans+=(x−1)ans+=(x-1) 。

代码

C++
#include<bits/stdc++.h>
using namespace std;
int t,nowcnt,op,ans,x,lastcnt;
int main()
{
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d",&nowcnt);
        op=0;
        ans=0;
        x=1;
        while(nowcnt)
        {
            printf("- %d\n",x);
            fflush(stdout);
            ans+=x;
            lastcnt=nowcnt;
            scanf("%d",&nowcnt);
            op=nowcnt+1-lastcnt;
            nowcnt-=op;
            int s=1;
            for(int i=1;i<=op;i++)
            {
                s*=2;
            }
            x=s;
            if(nowcnt==0)
            {
                ans+=(x-1);
            }
        }
        printf("! %d\n",ans);
        fflush(stdout);
    }
    return 0;
}

注意

这是一道交互题,别忘了 fflush(stdout)fflush(stdout) 。

这题是多测,记得输入 T 。

原文