洛谷P1582 倒水 二进制运算

xiaoxiao2021-02-28  90

题目连接 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; }
转载请注明原文地址: https://www.6miu.com/read-35945.html

最新回复(0)