zoukankan      html  css  js  c++  java
  • POJ 3253 Fence Repair(优先队列,哈夫曼树,模拟)

    题目

    //做哈夫曼树时,可以用优先队列(误?)

    //这道题教我们优先队列的一个用法:取前n个数(最大的或者最小的)

    //哈夫曼树
    //64位
    //超时->优先队列,,,,
    //这道题的优先队列用于取前2个小的元素
    
    #include <iostream>
    #include<stdio.h>
    #include<string.h>
    #include<algorithm>
    #include<queue>
    using namespace std;
    
    __int64 ans,a[20010];
    int n;
    
    struct cmp
    {  
        bool operator ()(__int64 &a,__int64 &b){  
            return a>b;
        }  
    };
    
    priority_queue<__int64,vector<__int64>,cmp> q;
    
    void hfm()
    {
        
        __int64 min1,min2,neww,yi;
        while(n>1)
        {
            yi=0;
            min1=q.top();
            q.pop();
            min2=q.top();
            q.pop();
            neww=min1+min2;
            ans+=neww;
            q.push(neww);
            n--;
        }
    }
    
    int main()
    {
        int i;
        while(scanf("%d",&n)!=EOF)
        {
            while(!q.empty())q.pop();
            for(i=0;i<n;i++)
            {
                scanf("%I64d",&a[i]);
                q.push(a[i]);
            }
            ans=0;
            if(n>1)
                hfm();
            else
                ans=a[0];
            printf("%I64d
    ",ans);
        }
        return 0;
    }
    View Code

    //这是我旁边的小学妹写的,不用优先队列也不会超时,可以过耶,我脑子太不灵光了,,,居然一直没想到,,,

    //小学妹的AC代码留念:

    #include<iostream>
    #include<algorithm>
    #include<cstdio>
    
    using namespace std;
    
    int main()
    {
        int n,length[20010];
        int i,j,sum;
        __int64 ans;
        while(cin>>n)
        {
            for(i=0;i<n;i++)
                cin>>length[i];
            sort(length,length+n);
            sum = 0;
            ans = 0;
            for(i=0;i<n-1;i++)
            {
                sum = length[i] + length[i+1];
                ans += sum;
                for(j=i+2;j<n;j++)
                {
                    if(sum > length[j])
                        length[j-1] = length[j];
                    else
                    {
                        length[j-1] = sum;
                        break;
                    }
                }
                if(j==n)
                    length[j-1] = sum;
            }
            cout<<ans<<endl;
        }
        return 0;
    }
    View Code
    一道又一道,好高兴!
  • 相关阅读:
    09 Django组件之用户认证组件
    二叉树的三种遍历(非递归)
    CoderForce 141C-Queue (贪心+构造)
    CoderForce 140C-New Year Snowmen(贪心)
    UVA-1663 Purifying Machine (最大匹配数)
    UVA-10801 Lift Hopping (最短路)
    UVA-1660 Cable TV Network (最小割)
    UVA-820 Internet Bandwidth (最大流)
    UVA-1336 Fixing the Great Wall(区间DP)
    棋盘分割(二维区间DP)
  • 原文地址:https://www.cnblogs.com/laiba2004/p/3808955.html
Copyright © 2011-2022 走看看