题解:P11968 「ALFR Round 7」T1 二进制与一 II
Lele_Programmer · · 题解
P11968 题解
思路
由高位向低位枚举每一位
如果没有剩余的
如果剩下有
一种方式是,枚举到
另一种,枚举到
不难发现刚刚两种情况中,剩下的
还有一种情况,枚举到某一位
代码
#define int long long
#define i32 signed
const int N=63;
const int inf=9e18;
int T,x,k;
int a[N];
i32 main() {
// FRR("A.in");
// FRW("A.out");
read(T);
while (T--) {
read(x),read(k);
int p=x;
memset(a,0,sizeof(a));
int ans=inf;
int idx=0;
while (x) a[++idx]=x&1,x>>=1;
// printf("a: "); _rep(i,1,N-1) write(a[i]); putchar(10);
int cnt=0;
_rep(i,1,N-1) cnt+=a[i];
if (k==cnt) {
writeln(0);
continue;
}
// ans=min(ans,abs(p-((1LL<<k)-1)));
int cur=0;
_rrep(i,N-1,1) {
if (k>i) break;
int j=(1LL<<k)-1;
_reps(s,k,i-1,(j<<=1,s++)) ans=min(ans,abs(p-(cur+j)));
// cout<<i<<" "<<cur<<endl;
k--,cur+=(1LL<<(i-1));
// cout<<cur<<endl;
cur+=(1LL<<k)-1;
// cout<<cur<<endl;
ans=min(ans,abs(cur-p));
cur-=(1LL<<k)-1;
if (!a[i]) k++,cur-=(1LL<<(i-1));
if (!k) break;
}
writeln(ans);
}
return 0;
}