牛客假日团队赛2 - C - 修围栏(思维)

题目链接:https://ac.nowcoder.com/acm/contest/924/C

思路:每次找出两块长度最短的木板,然后把它们合并,加入到集合中,然后在集合中找出两块长度最短的木板,合并,并把合并的长度加入到集合中,重复此过程,直到集合中只剩下一个元素,这个过程可以用优先队列维护。

#include <bits/stdc++.h>
using namespace std;
#define ll long long
const int N = 2e4 + 7;
int a[N];
priority_queue <int, vector <int>, greater<int> > Q;
int main()
{
    int n, x, y; ll ans = 0;
    scanf("%d",&n);
    for(int i = 0; i < n; i++)
    {
        scanf("%d", &x);
        Q.push(x);
    }
    while(Q.size() >= 2)
    {
        x = Q.top(); Q.pop();
        y = Q.top(); Q.pop();
        Q.push(x + y);
        ans += x + y;
    }
    cout << ans << endl;
}

猜你喜欢

转载自blog.csdn.net/sugarbliss/article/details/92406715