蒟蒻求助QAQ反悔贪心
查看原帖
蒟蒻求助QAQ反悔贪心
159959
虫洞吞噬者楼主2022/7/20 17:43

RTRT,我的思路大致就是把差分的数值作为链接的花费,然后其他的贪心策略以及代码的实现基本与种树那道题类似

但在处理坐标时,一直出问题QAQ

求大佬斧正QAQ

code:

#include<bits/stdc++.h>
using namespace std;
#define int long long
int n,k,ans,tot,pre;
int l[200200],r[200200],w[200200],num[200200],vis[200200];
struct node{
	int id,w;
	friend bool operator<(node a,node b)
	{
		return a.w>b.w;
	}
}cur,nxt;
priority_queue<node>q;
signed main()
{
	scanf("%lld%lld%lld",&n,&k,&pre);
	for(int i=1;i<n;++i)
	{
		scanf("%lld",&num[i]);
		w[i]=num[i]-pre;
		pre=num[i];
	}
	for(int i=1;i<n;++i)
	{
		++tot;
		if(i==1)
		{
			l[i]=-1;
			r[i]=i+1;
		}
		else if(i==n-1)
		{
			l[i]=i-1;
			r[i]=-1;
		}
		else 
		{
			l[i]=i-1;
			r[i]=i+1;
		}
		cur.id=tot;
		cur.w=w[i];
		q.push(cur);
	}
	for(int i=1;i<=k;++i)
	{
		while(vis[q.top().id])q.pop();
		ans+=q.top().w;
		int cid=q.top().id,cw=q.top().w;
		q.pop();
		++tot;
		vis[l[cid]]=1;vis[r[cid]]=1;
		l[r[r[cid]]]=tot;r[l[l[cid]]]=tot;
		l[tot]=l[l[cid]];r[tot]=r[r[cid]];
		w[tot]=w[l[cid]]+w[r[cid]]-cw;
		nxt.id=tot;
		nxt.w=w[tot];
		q.push(nxt);
	}
	printf("%lld",ans);
	return 0;
}
2022/7/20 17:43
加载中...