• 石子合并问题 -- 任意版


    有N堆石子,现要将石子有序的合并成一堆,规定如下:每次只能移动任意的2堆石子合并,合并花费为将的一堆石子的数量。设计一个算法,将这N堆石子合并成一堆的总花费最小(或最大)。

    此类问题比较简单,就是哈夫曼编码的变形,用贪心算法即可求得最优解。即每次选两堆最少的,合并成新的一堆,直到只剩一堆为止。证明过程可以参考哈夫曼的证明过程。

           代码如下:

    #include <iostream>
    #include <fstream>
    #include <deque>
    #include <algorithm>
    using namespace std;
    
    struct Node
    {
        int key;
        Node* left;
        Node* right;
        Node(){left=0;right=0;}
    };
    
    deque<Node*>forest;
    ifstream fin("in.txt");
    static int min = 0;
    
    bool compare(Node* a,Node* b)
    {
        return a->key < b->key;    //求最小组合
        //return a->key > b->key;  //求最大组合
    } 
    
    void print(Node *head)
    {
        if(head->left)
        {
            cout<<head->key<<"  ";
            print(head->left);
            print(head->right);
            min=min+head->key;
        }
        return;
    }
    
    int main()
    {
        int n;
        fin>>n;
        Node *p;
        for(int i=0;i<n;i++)
        {
            p=new Node;
            fin>>p->key;
            forest.push_back(p);
        }
    
    /*    //反向迭代器 逆序输出 也可用来求最大值
        deque<Node*>::reverse_iterator rit;
        rit = forest.rbegin();
    
        for(i=0;i<n;i++)
        {
            cout<<" - "<<rit[i]->key<<endl;
        }
    */
        for(i=0;(i<n) && (forest.size()>1);i++)
        {    
            sort(forest.begin(),forest.end(),compare);
            p = new Node;
            p->key = forest[0]->key  + forest[1]->key;
            p->left = forest[0];
            p->right = forest[1];
            forest.pop_front();
            forest.pop_front();
            forest.push_back(p);
        }
        p = forest.front();
        print(p);
        cout<<endl<<"min:"<<min<<endl;
        
        return 0;
    }

    输入文件: in.txt 

    10
    2 4 5 6 4 10 3 6 8 1

    输出结果:

    49  21  11  28  12  6  3  16  8
    min:154
    Press any key to continue

  • 相关阅读:
    Paxos算法简单陈述
    二段式提交和三段式提交
    Guava包学习--Hash
    JedisPool无法获得资源问题
    有料面试题之--Object里面的方法
    Spring常用jar包的功能
    线上日志分析与其他一些脚本
    Flutter-漸變色按鈕
    Flutter-自定義圖標或者選擇框
    Flutter-自定義圖片圖標
  • 原文地址:https://www.cnblogs.com/yezhennan/p/5443609.html
Copyright © 2020-2023  润新知