題目連接
https://www.luogu.org/problem/show?pid=1582
因爲無論怎麼倒水瓶中水只會是1,2,4,8,16…的狀態,想到用二進制表示狀態。
1表示瓶中有水,0表示沒有,只要讓N中的1變成K個就可以了;
在計數N中的一時用到(n&-n),然後每次要去掉最後的1,這時n+(n&-n);
#include<iostream>
#include<cstdio>
int n,k,ans;
using namespace std;
int Count(int x){
int s=0;
while(x){
x=x-(x&-x);
s++;
}
return s;
}
int main(){
cin>>n>>k;
while(Count(n)>k){
n=n+(n&-n);
ans=ans+(n&-n);
}
cout<<ans;
return 0;
}