合并石子(优先队列方法)

//优先队列方法
#include 
#include 
#define maxn 100005
using namespace std;
int main () {
    int n;
    long long ans = 0;
    int a[maxn],b[maxn]={0};
    cin >> n;
    for (int i=0;i) {
        cin >> a[i];
    }
    sort (a,a+n);
    a[n] = 999999999;
    a[n+1] = 999999999;
    int fa=0,fb=0,ok,pos_b=0,sum;
    for (int i=0;i1;i++) {
        sum = a[fa] + a[fa+1]; ok = 1;
        if (a[fa] + b [fb] < sum && b[fb]) {ok = 2;sum = a[fa] + b[fb];}
        if (b[fb] + b[fb+1] < sum && b[fb] && b[fb+1]) {ok = 3;sum = b[fb] + b[fb+1];}
        b[pos_b++] = sum;
        switch (ok) {
            case 1: fa += 2; break;
            case 2: fa++;fb++; break;
            case 3: fb +=2; break;
        }
        ans += sum;
    }
    cout << ans << endl;
}

 

转载于:https://www.cnblogs.com/xiaoshanshan/p/3557154.html

你可能感兴趣的:(合并石子(优先队列方法))