1. 程式人生 > >【霍夫曼樹】poj 1339 poker card game

【霍夫曼樹】poj 1339 poker card game

game 霍夫曼樹 printf i++ OS IT amp ostream ++

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; }

【霍夫曼樹】poj 1339 poker card game