种树[堆][贪心][链表]

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 17:13   1299   0

传送门


#include<bits/stdc++.h>
#define N 200050
using namespace std;
int n,m,a[N],l[N],r[N],flag[N],ans;
struct Node{
 int x,val;
 bool operator < (const Node &a) const{
  return a.val > val;
 }
};
priority_queue<Node> q;
void Delete(int x){flag[x]=1 , l[r[x]]=l[x] , r[l[x]]=r[x];}
int main(){
 scanf("%d%d",&n,&m); if(m>n/2){printf("Error!"); return 0;}
 for(int i=1;i<=n;i++){
  scanf("%d",&a[i]); q.push(Node{i,a[i]});
  l[i]=i-1 , r[i]=i+1;
 }l[1]=n , r[n]=1;
 for(int i=1;i<=m;i++){
  while(!q.empty() && flag[q.top().x]) q.pop();
  Node X = q.top(); q.pop();
  ans += X.val; int L=l[X.x] , R=r[X.x];
  a[X.x]=a[L]+a[R]-X.val;
  q.push(Node{X.x,a[X.x]}); 
  Delete(L) , Delete(R);
 }printf("%d",ans); return 0;
} 

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP