bzoj1150

经典题解:选择与放弃

这是一道经典题目,不过易错点就是最后注意如果要选最后一个点的话,那么他前一个点就一定不会选了。

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<queue>
using namespace std;
typedef long long ll;
struct node
{
	int f, n, v,num;
};
bool operator<(const node &a, const node &b)
{
	return a.v > b.v;
}
priority_queue<node, vector<node> >que;
node nod[200010];
int n, k;
bool isclear[200010];
int alltot;
int main()
{
	scanf("%d%d", &n, &k);
	int now, last;
	alltot = 1;
	scanf("%d", &last);
	for (int i = 1; i <= n-1; i++)
	{
		scanf("%d", &now);
		nod[alltot].v = now - last;
		nod[alltot].f = alltot - 1;
		nod[alltot].n = alltot + 1;
		nod[alltot].num = alltot;
		last = now;
		alltot++;
	}
	alltot--;
	nod[alltot].n = 0;
	for (int i = 1; i <= alltot; i++)
		que.push(nod[i]);
	ll ans = 0;
	while (k)
	{
		node kk;
		do{
			 kk= que.top();
			que.pop();
		} while (isclear[kk.num]);
		ans += kk.v;
		int f = nod[kk.num].f;  int n = nod[kk.num].n;
		int gf = nod[f].f; int gn = nod[n].n;
		isclear[kk.num] = 1; isclear[f] = 1; isclear[n] = 1;
		if (n == 0)
		{
			nod[gf].n = 0;
			k--;
			continue;
		}
		if (f == 0)
		{
			nod[gn].f = 0;
			k--;
			continue;
		}
		alltot++;
		nod[alltot].v = nod[f].v + nod[n].v - kk.v; nod[alltot].num = alltot;
		nod[alltot].f = gf; nod[gf].n = alltot;
		nod[alltot].n = gn; nod[gn].f = alltot;
		que.push(nod[alltot]);
		k--;
	}
	printf("%lld\n", ans);
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值