51nod-1596-搬货物

现在有n个货物,第i个货物的重量是 2 w i 。每次搬的时候要求货物重量的总和是一个2的幂。问最少要搬几次能把所有的货物搬完。

样例解释:

1,1,2作为一组。

3,3作为一组。

Input
单组测试数据。
第一行有一个整数n (1≤n≤10^6),表示有几个货物。
第二行有n个整数 w1,w2,…,wn,(0≤wi≤10^6)。
Output
输出最少的运货次数。
Sample Input
样例输入1
5
1 1 2 3 3
Sample Output
样例输出1
2


我们知道, 2 x + 2 x = 2 x + 1 .
于是,这道题就成功转化成了大暴力(?)。
(话题上标的是二进制…
读入时记录每一位的个数。
枚举每一位,进位,答案加上这一位的数字。
然后,我做出来的竟然要用读入优化(否则T掉)。不知道有没有什么优化之类的。
存在进位,所以不能只枚举到最大值,需要再多枚举几位。
详见代码。

#include<cstdio>
#include<algorithm>
#define maxn 1000100
using namespace std;
int n,cnt[maxn+5],ans,m;
int getint()
{
    int res=0;
    char c=0;
    while(c<'0'||c>'9') c=getchar();
    while(c>='0'&&c<='9')
    {
        res=res*10+c-'0';
        c=getchar();
    }
    return res;
}
int main()
{
    n=getint();
    for(int i=1;i<=n;i++)
    {
        int x=getint();
        cnt[x]++;
        m=max(m,x);
    }
    for(int i=0;i<=m+100;i++)
    {
        if(cnt[i]>1)
        {
            cnt[i+1]+=cnt[i]>>1;
            cnt[i]&=1;
        }
        ans+=cnt[i];
    }
    printf("%d\n",ans);
}

猜你喜欢

转载自blog.csdn.net/dogeding/article/details/79331066