POJ 3253 Fence Repair
题目大意:
农夫约翰为了修理栅栏 要将一块很长的木板切成 $N$ 块 准备切成的木板长度为 $L1, L2, L3......$ 未切割前木板长度刚好是切后木板长度和 每次切断木板的时候 需要的开销为这段木板的长度
样例:
$N = 3, L = {8, 5, 8}$
输出: 34
时间复杂度:$O(N ^ 2)$
代码1:
const int maxn = 1e5 + 10; int N, L[maxn]; typedef long long l1; void solve() { l1 ans = 0; while(N > 1) { int mii1 = 0, mii2 = 1; if(L[mii1] > L[mii2]) swap(mii1, mii2); for(int i = 2; i < N; i ++) { if(L[i] < L[mii1]) { mii2 = mii1; mii1 = i; } } int t = L[mii1] + L[mii2]; ans += t; if(mii1 == N - 1) swap(mii1, mii2); L[mii1] = t; L[mii2] = L[N - 1]; N --; } printf("%lld\n", ans); }
时间复杂度:$O(N * logN)$
代码2:
const int maxn = 1e5 + 10; int N, L[maxn]; typedef long long l1; void solve() { priority_queue<int, vector<int>, greater<int>> que; for(int i = 0; i < N; i ++) que.push(L[i]); while(que.size() > 1) { int l1, l2; li = que.top(); que.pop(); l2 = que.top(); que.pop(); ans += l1 + l2; que.push(l1 + l2); } printf("%lld\n", ans); }