zoukankan      html  css  js  c++  java
  • 寒假Day34:POJ3253Fence Repair 哈夫曼树+优先队列

     POJ - 3253

    样例:

    Sample Input
    3
    8
    5
    8
    
    Sample Output
    34

    题意:看下题目Hint部分就可以了

    思路:每次取所有木板中最短的两块构成一块新木板(新木板的长度等于那两块的和),将此木板放回到原来所有木板中进行比较,再选出最短的两块来,以此类推,求拼接成一整块木板的最短长度。

    我看貌似这个就是单调队列了。

    哈夫曼树+优先队列写法AC代码:

    #include<stdio.h>
    #include<string.h>
    #include<iostream>
    #include<queue>
    using namespace std;
    typedef long long ll;
    
    int main()
    {
        int n;
        while(cin>>n)
        {
            priority_queue<int,vector<int>,greater<int> >Q;
            for(int i=1; i<=n; i++)
            {
                ll x;
                cin>>x;
                Q.push(x);
            }
            ll sum=0;
            while(Q.size()>1)
            {
                ll p=Q.top();
                Q.pop();
                ll q=Q.top();
                Q.pop();
                Q.push(p+q);
                sum=sum+p+q;
            }
            cout<<sum<<endl;
        }
        return 0;
    }

    另外一种写法:

    #include<iostream>
    #include<string.h>
    #include<queue>
    #include<stack>
    #include<cmath>
    #include<map>
    #include<algorithm>
    #define inf 0x3f3f3f3f
    typedef long long ll;
    using namespace std;
    
    int a[20020];
    
    int main()
    {
        std::ios::sync_with_stdio(false);
        cin.tie(0);
        cout.tie(0);
        int n;
        while(cin>>n)
        {
            memset(a,0,sizeof(a));
            for(int i=0;i<n;i++)
                cin>>a[i];
            ll ans=0;
            while(n>1)
            {
                int mi1=0,mi2=1;
                if(a[mi1]>a[mi2])
                    swap(mi1,mi2);
                for(int i=2;i<n;i++)
                {
                    if(a[i]<a[mi1])
                    {
                        mi2=mi1;
                        mi1=i;
                    }
                    else if(a[i]<a[mi2])
                        mi2=i;
                }
                int t=a[mi1]+a[mi2];
                ans=ans+t;
                if(mi1==n-1)
                    swap(mi1,mi2);
                a[mi1]=t;
                a[mi2]=a[n-1];
                n--;
            }
            cout<<ans<<endl;
        }
        return 0;
    }
    View Code
  • 相关阅读:
    并查集基础练习
    HDU1232——畅通工程
    二分答案——划分数列
    二分答案——收入计划
    动态规划练习题(2)
    动态规划程序设计2
    动态规划练习题(1)
    0/1背包
    P5024 保卫王国[倍增+dp]
    UVA11424 GCD
  • 原文地址:https://www.cnblogs.com/OFSHK/p/12369807.html
Copyright © 2011-2022 走看看