1. 程式人生 > >【貪心】CODE[VS] 1063 NOIP2004普及組-合併果子 (刷題記錄(模擬+優先佇列))

【貪心】CODE[VS] 1063 NOIP2004普及組-合併果子 (刷題記錄(模擬+優先佇列))

日常水題
貪心策略:每次找代價最小的兩對合並,用小根堆來維護,每次合併之後將當前合併結果重新推入佇列,直到合併完成(n-1次)

程式碼如下

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <queue>

using namespace std;
typedef long long LL;

LL n;
LL tot,ans;
priority_queue<LL ,vector
<LL >
,greater<LL > >q; int main() { scanf("%lld",&n); for(LL i = 1;i <= n;i++) { LL aa; scanf("%lld",&aa); q.push(aa); } while(q.size() != 1) { LL u = q.top(); q.pop(); LL v = q.top(); q.pop(); //cout<<"tot_after : "<<tot<<endl;
tot = u+v; //cout<<"tot_fin : "<<tot<<endl; ans += tot; q.push(tot); //cout<<"ans : "<<ans<<endl; } printf("%lld\n",ans); return 0; }

THE END

By Peacefuldoge