Programming Algorithms-Fence repair (Fence Repair) code (C)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.