优先队列,链表优化
8.整数删除 - 蓝桥云课
#include<bits/stdc++.h>
#define int long long
using namespace std;
typedef pair<int,int>p;
const int A=5e5+10;
int s[A];
int l[A];
int r[A];
signed main()
{// 请在此输入您的代码priority_queue<p,vector<p>,greater<p>>q;int N,K;cin>>N>>K;for(int i=1;i<=N;i++){cin>>s[i];q.push({s[i],i});l[i]=i-1;r[i]=i+1;if(r[i]==N+1){r[i]=-1;}}while(K){p t=q.top();q.pop();if(t.first!=s[t.second]){q.push({s[t.second],t.second});continue;}K--;if(l[t.second]>=1){s[l[t.second]]+=t.first;}if(r[t.second]>=1){s[r[t.second]]+=t.first;}if(l[t.second]>=1){r[l[t.second]]=r[t.second];}if(r[t.second]>=1){l[r[t.second]]=l[t.second];}s[t.second]=-1;}for(int i=1;i<=N;i++){if(s[i]!=-1){cout<<s[i]<<" ";}}return 0;
}
为了找到每一次更新数组后的最小值,所以想到使用小顶堆来实现,小顶堆的定义:
priority_queue<p,vector<p>,greater<p>>q;
为了确定每一个数值的位置信息,从而更方便的用链表来维护这个数组,所以小顶堆是pair类型的,定义l,r数组来存储每个节点的左右坐标值,同时将超过数组范围的右节点定义为-1,方便后面的维护。
操作逻辑:循环操作次数,但这里不能简单的进行K--,因为如果取出的堆顶元素不等于堆顶元素下标值所对应的原数组元素,这是因为每一次操作时,数组中的元素的值会发生变化,所以变化后的元素值和下标需要push进堆中重新维护,这次操作不计入操作次数,所以操作次数是否减少要进行这个判断。
p t=q.top();q.pop();if(t.first!=s[t.second]){q.push({s[t.second],t.second});continue;}K--;
在进行完上面的判断后,要开始对数组进行更改:
if(l[t.second]>=1){s[l[t.second]]+=t.first;}if(r[t.second]>=1){s[r[t.second]]+=t.first;}if(l[t.second]>=1){r[l[t.second]]=r[t.second];}if(r[t.second]>=1){l[r[t.second]]=l[t.second];}s[t.second]=-1;}
对值更改:如果节点的左右节点没有越界,节点值加上堆顶值。
对下标的更改:当前节点的左节点的右节点等于当前节点的右节点,当前节点的右节点的左节点等于当前节点的左节点(删节点通用)。