zoukankan      html  css  js  c++  java
  • poj3253 Fence Repair **

    /*
    * 3253 Fence Repair.cpp
    *
    * Created on: 2011-10-25
    *
    * Huffman + 堆排
    *
    * _int64 让我WA了无数次, 郁闷
    *
    */

    #include <iostream>
    using namespace std;

    const int maxn = 50000 + 5;
    __int64 len[maxn], n, size;

    inline int left(int i){
    return 2 * i + 1;
    }
    inline int right(int i){
    return 2 * i + 2;
    }
    inline int parent(int i){
    if(i == 0) return -1;
    return (i-1)/2;
    }

    void minHeapify(int x){
    int y = left(x);
    int tmp = len[x];
    while(y < size){
    if(y < size-1 && len[y+1] < len[y])
    y = y+1;
    if(len[y] >= tmp)
    break;
    len[x] = len[y];
    x = y;
    y = left(x);
    }
    len[x] = tmp;
    }

    void makeHeap(){
    for(int i=size/2-1; i>=0; i--)
    minHeapify(i);
    }

    int extractMin(){
    if(size == 0) return -1;

    int tmp = len[0];
    len[0] = len[--size];
    minHeapify(0);

    return tmp;
    }

    void insert(int key){
    int pos = size++;
    while(parent(pos) >= 0 && len[parent(pos)] > key){
    len[pos] = len[parent(pos)];
    pos = parent(pos);
    }
    len[pos] = key;
    }



    void buildHuffman(){
    __int64 a, b, c, sum = 0;

    while(size >= 2){
    a = extractMin();
    b = extractMin();

    c = (a + b);
    sum += c;

    insert(c);
    }

    cout << sum << endl;
    }


    int main(){
    while(cin >> n){
    for(int i=0; i<n; i++)
    cin >> len[i];
    size = n;

    if(n == 1){
    cout << 0 << endl;
    continue;
    }

    makeHeap();

    buildHuffman();
    }

    return 0;
    }
  • 相关阅读:
    webOFBiz10.4
    堆栈知识
    eas bos二次开发总结[第三方jar、jcom、二次开发包放置]
    计算机编程英语词汇(三)
    计算机英语(四)
    KDTable 表达式应用工具类
    Verilog 流水线加法器
    datagridview 积累
    ajax 调用 webserver
    windows7 vs2008问题结合
  • 原文地址:https://www.cnblogs.com/longdouhzt/p/2246094.html
Copyright © 2011-2022 走看看