1. 程式人生 > 其它 >P1090 [NOIP2004 提高組] 合併果子 / [USACO06NOV] Fence Repair G 題解

P1090 [NOIP2004 提高組] 合併果子 / [USACO06NOV] Fence Repair G 題解

P1090 [NOIP2004 提高組] 合併果子 / [USACO06NOV] Fence Repair G
這是一道貪心演算法的題目,每次選擇兩個最小的堆,合併後,繼續直到只有一堆為止,可能用優先佇列進行維護。

#include<bits/stdc++.h>
using namespace std;
int main()
{
priority_queue<int,vector<int>,greater<int> > q;
int n;
cin>>n;
for (int i=1;i<=n;i++)
{
int x;
cin>>x;
q.push(x);
}
int ans=0;
while(q.size()>1)
{
int x,y;
x=q.top();
q.pop();
y=q.top();
q.pop();
int z;
z=x+y;
ans+=z;
q.push(z);
}
cout<<ans;
return 0;
}