【霍夫曼树】poj 1339 poker card game (数组排序+辅助队列的方法,预处理O(nlogn),构造霍夫曼树O(n))

poj.org/problem?id=1339

#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
#include<queue>

using namespace std;
int n;
const int maxn=1e5+2;
int main(){
    int T;
    scanf("%d",&T);
    while(T--){
        priority_queue<int,vector<int>,greater<int> > pq;    
        scanf("%d",&n);
        int x;
        for(int i=0;i<n;i++){
            scanf("%d",&x);
            pq.push(x);
        }
        int ans=0;
        n--;
        while(n--){
            int x=pq.top();
            pq.pop();
            int y=pq.top();
            pq.pop();
            int z=x+y;
            pq.push(z);
            ans+=z;
        }
        printf("%d\n",ans);
    }
    return 0;
}

 方法二

数组排序+辅助队列(利用新加进来的内结点的单调性)

#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
#include<queue>
#include<cmath>
using namespace std;
int n;
const int maxn=1e5+2;
int a[maxn];
int main(){
    int T;
    scanf("%d",&T);
    while(T--){
        scanf("%d",&n);
        for(int i=0;i<n;i++){
            scanf("%d",&a[i]);
        }
        sort(a,a+n);
        queue<int> Q;
        int ans=0;
        int l=0;
        int t=n-1;
        while(t--){
            int tmp=0;
            for(int i=0;i<2;i++){
                if(!Q.empty()&&(l>=n||Q.front()<=a[l])){
                    tmp+=Q.front();
                    Q.pop();
                }else{
                    tmp+=a[l];
                    l++;
                }
            }    
            Q.push(tmp);
            ans+=tmp;
        }
        printf("%d\n",ans);
    }
    return 0;
}

 

posted @ 2018-06-14 10:50  shulin15  阅读(235)  评论(0编辑  收藏  举报