CodeForces 884D Boxes And Balls 哈夫曼樹+優先權隊列

這道題要用哈夫曼樹,不過k=3或2。一開始想到補0,需要補的個數爲k-(n-1)%(k-1)-1。但後來發現,哈夫曼樹≠平衡樹,n=3的時候都會出現問題。然後多試了幾個例子(n=2,3,4,5,6,7,8,9),發現當n是偶數的時候,需要將最小的兩個數相加(k=2),然後剩下的情況都是k=3;而n是奇數的時候,全部k=3就可以。

用優先權隊列來做:

#include<queue>
using namespace std;
priority_queue<int,vector<int>,less<int> >que; //從大到小
priority_queue<int,vector<int>,greater<int> >que; //從小到大

附上AC代碼:

#include<cstdio>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
#define ll long long
const int INF=0x3f3f3f3f;

//priority_queue<int,vector<int>,less<int> >que; //從大到小
priority_queue<ll,vector<ll>,greater<ll> >que; //從小到大
///注意long long類型!
int main()
{
    int n;
    while(scanf("%d",&n)==1)
    {
        while(!que.empty()) que.pop();//清空隊列
        ll x;
        for(int i=0;i<n;i++)
        {
            scanf("%lld",&x);
            que.push(x);
        }
        if(n==1)
        {
            printf("0\n");
            continue;
        }
        ll ans=0;
        if(que.size()%2==0)//n是偶數,第一步兩個數相加
        {
            ll t=que.top(); que.pop();
            t+=que.top(); que.pop();
            ans+=t;
            que.push(t);
        }
        while(que.size()>1)
        {
            ll t=que.top(); que.pop();
            t+=que.top(); que.pop();
            t+=que.top(); que.pop();
            ans+=t;
            que.push(t);
        }
        printf("%lld\n",ans);
    }
	return 0;
}

/**
6
1 4 4 4 4 4
ans=38

7
1 4 4 4 4 4 4
ans=46
**/

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章