luogu P1582 倒水 |数学

题目描述

一天,CC买了N个容量可以认为是无限大的瓶子,开始时每个瓶子里有1升水。接着~~CC发现瓶子实在太多了,于是他决定保留不超过K个瓶子。每次他选择两个当前含水量相同的瓶子,把一个瓶子的水全部倒进另一个里,然后把空瓶丢弃。(不能丢弃有水的瓶子)

显然在某些情况下CC无法达到目标,比如N=3,K=1。此时CC会重新买一些新的瓶子(新瓶子容量无限,开始时有1升水),以到达目标。

现在CC想知道,最少需要买多少新瓶子才能达到目标呢?

输入格式

一行两个正整数, N,K(1le Nle 2 imes 10^9,Kle 10001≤N≤2×10,K≤1000)。

输出格式

一个非负整数,表示最少需要买多少新瓶子。


#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
int num(int x){
    int ans=0;
    while(x){ans++;x-=x&(-x);}
    return ans;
}
int main()
{
    int n,k;
    cin>>n>>k;int ans=0;
    while(num(n)>k){
	ans+=n&(-n);
	n+=n&(-n);
    }
    cout<<ans<<endl;
}
原文地址:https://www.cnblogs.com/naruto-mzx/p/11847646.html