1. 程式人生 > >[POJ 3253] Fence Repair

[POJ 3253] Fence Repair

++ har mat bsp 編碼 http push n) nbsp

[題目鏈接]

http://poj.org/problem?id=3253

[算法]

首先, 進行了(n - 1)次切割後,原木板一定被切成了a1,a2,a3...an共n塊

我們不妨考慮從終止狀態到開始狀態的最小代價,這與原問題是完全等價的,不難看出最後的答案就是哈夫曼最優編碼

[代碼]

#include <algorithm>  
#include <bitset>  
#include <cctype>  
#include <cerrno>  
#include 
<clocale> #include <cmath> #include <complex> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <deque> #include <exception> #include <fstream> #include <functional> #include <limits> #include
<list> #include <map> #include <iomanip> #include <ios> #include <iosfwd> #include <iostream> #include <istream> #include <ostream> #include <queue> #include <set> #include <sstream> #include <stdexcept> #include
<streambuf> #include <string> #include <utility> #include <vector> #include <cwchar> #include <cwctype> #include <stack> #include <limits.h> using namespace std; typedef long long ll; int i,n,x,y; ll ans; priority_queue< ll,vector<ll>,greater<ll> > q; namespace IO { template <typename T> inline void read(T &x) { int f = 1; x = 0; char c = getchar(); for (; !isdigit(c); c = getchar()) { if (c == -) f = -f; } for (; isdigit(c); c = getchar()) x = (x << 3) + (x << 1) + c - 0; x *= f; } template <typename T> inline void write(T x) { if (x < 0) { putchar(-); x = -x; } if (x > 9) write(x / 10); putchar(x % 10 + 0); } template <typename T> inline void writeln(T x) { write(x); puts(""); } } ; int main() { IO :: read(n); for (i = 1; i <= n; i++) { IO :: read(x); q.push(x); } while (q.size() > 1) { x = q.top(); q.pop(); y = q.top(); q.pop(); ans += x + y; q.push(x + y); } IO :: writeln(ans); return 0; }

[POJ 3253] Fence Repair