[Ybt high-efficiency advanced 4-1-1] [luogu P1090] merge fruit / Fence Repair G

Fence Repair G

Topic link: ybt efficient advanced 4-1-1 / luogu P1090

General idea

There are a bunch of things. Each time you can choose two things, and at the cost of their size and sum, combine them to get one thing with their size and sum.
Then combine them into one thing at the least cost.

Ideas

We consider being greedy, so that the cost of each merger is as small as possible.

Naturally, I can choose the smallest two of the existing stones to merge each time.

Then you can use the heap for maintenance, and then you can.

Code

#include<queue>
#include<cstdio>
#define ll long long

using namespace std;

int n;
priority_queue <ll, vector<ll>, greater<ll> > q;
ll ans, x, y;

int main() {
    
    
	scanf("%d", &n);
	for (int i = 1; i <= n; i++) {
    
    
		scanf("%lld", &x);
		q.push(x);
	}
	
	while (!q.empty()) {
    
    
		x = q.top();
		q.pop();
		y = q.top();
		q.pop();
		
		ans += x + y;//代价
		if (q.empty()) {
    
    //只剩一个
			break;
		}
		q.push(x + y);//得到新的东西
	}
	
	printf("%lld", ans);
	
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_43346722/article/details/114647239