POJ 3253 Fence Repair


優先隊列+容器

Memory Limit Exceeded

#include <stdio.h>
#include <stdlib.h> 
#include <iostream> 
#include <vector>
#include <queue>
using namespace std;

int
main()
{
    priority_queue<long long int, vector<long long int>, greater<long long int> >my;
    long long int t, a, b, temp, sum;

    while(cin>>t, t){
        while(my.empty()!=1)my.pop();

        while(t--){
            cin>>temp;
            my.push(temp);
        }
        sum=0;
        while(my.size()>1){
            a=my.top(); my.pop();
            b=my.top(); my.pop();
            sum+=(a+b);
            my.push(a+b);
        }
        cout<<sum<<endl;
    }

    return 0;
}

網上的用類的實現  c++這個還不是很懂


#include <iostream> 
#include <queue>
#include <stdio.h>
using namespace std;


struct node
{
    long long int w;
    bool operator < (const node &a) const {
             return w>a.w;
         }      
//運算符的重載,一般重載"<"(sort使用可以不用寫cmp)
//重載相當於是  給結構體添加了一個屬性,添加了一個可以用來比較的小的屬性
}tmp;


int
main()
{
        int t, a, b;
        long long int sum;
        scanf("%d", &t);
        priority_queue<node> my;
        while(t--){
            scanf("%d", &tmp.w);
            my.push(tmp);
        }
        sum=0;
        while(my.size() > 1){
            a=my.top().w; my.pop();
            b=my.top().w; my.pop();
            tmp.w=(a+b);
            my.push(tmp);
            sum +=tmp.w;
        }
        printf("%lld\n", sum);
    


        return 0;
}

還有一種寫法是這樣的 用的是hesg_up()


#include <iostream>
#include <algorithm>
#include <functional>
using namespace std;

int main(int argc, char* argv[])
{
    long fence[20000];
    int N;
    scanf("%d", &N);

    for (int i = 0; i < N; ++i) scanf("%d", &fence[i]);

    make_heap(&fence[0],&fence[N],greater<long>());
    int n = N;
    long long cnt = 0;
    while(n > 1)
    {
        long long num1 = fence[0];
        pop_heap(&fence[0],&fence[n],greater<long>());
        --n;
        long long num2 = fence[0];
        pop_heap(&fence[0],&fence[n],greater<long>());
        fence[n-1] = num1 + num2;
        cnt += fence[n-1];
        push_heap(&fence[0],&fence[n],greater<long>());
    }
    cout << cnt << endl;
    return 0;
}


你可能感兴趣的:(POJ 3253 Fence Repair)