求助这个思路为什么是错的
查看原帖
求助这个思路为什么是错的
563650
haochengw920楼主2024/5/31 09:29

rt,每天默认购买这只股票,然后把它放到一个小根堆里,如果堆顶元素比它小就把堆顶卖掉,最后弹栈

这样一个元素要么被卖掉,要么被退掉,而且既买又卖似乎能合并成一个操作(这样就不用担心多次操作了),而且每次卖栈顶似乎是最优的?

#include<cstdio>
#include<queue>
#include<vector>
#include<algorithm>
#include<functional>
#define int long long
using namespace std;

int n, x, ans;
priority_queue<int, vector<int>, greater<int> >hp;

signed main()
{
	scanf ("%lld", &n);
	for (int i = 1; i <= n; ++ i) {
		int x;
		scanf ("%lld", &x);
		ans -= x;
		hp.push(x);
		if (x > hp.top())
			ans += x, printf ("%lld\n", hp.top()), hp.pop();
	}
	while (!hp.empty()) ans += hp.top(), hp.pop();
	return printf ("%lld\n", ans), 0;
}
2024/5/31 09:29
加载中...