Fence Repair (Fence Repair) code (C)
This address: Http://blog.csdn.net/caroline_wendy
Title: Cut a piece of wood into n blocks, cut two pieces at a time, the cost of the split is the length of the board, the minimum cost of dividing the board.
The Huffman Code (Huffman).
greedy algorithm , similar to two-fork tree structure, the shortest plate and the second short plate is the brothers node , select two minimum planks, the final division, merging Two minimum planks, in turn recursion.
Code:
/* * main.cpp * * Created on:2014.7.17 * author:spike *//*eclipse CDT, gcc 4.8.1*/#include <stdio.h> #inclu De <limits.h> #include <utility> #include <queue> #include <algorithm>using namespace Std;class Program {typedef long LONG ll;static const int max_n = 10000;int n=5, l[max_n]={1,2,3,4,5};p ublic:void solve () {ll 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;} else if (L[i]<l[mii2]) {mii2 = 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 ("result =%lld\n", ans);}; int main (void) {program P; P.solve (); return 0;}
Output:
result = 33
Programming Algorithms-Fence repair (Fence Repair) code (C)