51 nod 1596 搬货物 (优先队列水题)

题目来源: CodeForces
基准时间限制:1 秒 空间限制:131072 KB 分值: 10 难度:2级算法题
收藏
关注
取消关注

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

样例解释:

1,1,2作为一组。

3,3作为一组。


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

分析:将所有的货物放入优先队列(升序)。要想运送货物是2的幂,如果运一个肯定是2的幂,如果运两个则只要两个货物相等就也是2的幂。而2^x+2^x=2^(x+1),所以将两个货物合并成一个并不断更新队列即可。


不用加输出外挂,稳过。
#include <iostream>
#include <queue>
using namespace std;
typedef long long ll;
priority_queue<ll,vector<ll>,greater<ll> > que;

int main()
{
    ll n;
    ios::sync_with_stdio(false);
    while(cin>>n)
    {

        while(!que.empty())
            que.pop();
        while(n--)
        {
            int tmp;
            cin>>tmp;
            que.push(tmp);
        }
        ll ans=0;
        while(que.size()>=2)
        {
            ll a=que.top();
            que.pop();
            ll b=que.top();
            que.pop();
            if(a==b)
                que.push(a+1);
            else
                ans++,que.push(b);
        }
        ans++;
        cout<<ans<<endl;
    }
    return 0;
}

 

 
posted @ 2017-08-07 15:24  只有你  阅读(129)  评论(0编辑  收藏  举报