zoukankan      html  css  js  c++  java
  • 洛谷P1484种树(堆+较难贪心)

    题目链接:https://www.luogu.org/problemnew/show/P1484

    题意很清晰很好懂,做起来就难了。

    数据范围小的化可搜索可dp,

    But数据这么大是不可能的了,较难贪心(a[i]或左加右只选一个最大的)+堆(每次取出最大的)

     1 #include <iostream>
     2 #include <algorithm>
     3 #include <queue>
     4 using namespace std;
     5 typedef long long ll;
     6 const int maxn=1e6+5;
     7 ll a[maxn];
     8 int vis[maxn];
     9 int l[maxn],r[maxn];
    10 int n,k;
    11 int ans;
    12 struct px
    13 {
    14     ll v;
    15     int id;
    16     bool operator <(const px &a)const
    17     {
    18         return v<a.v;
    19     }
    20 }t;
    21 priority_queue<px> que;
    22 
    23 int main()
    24 {
    25     ios::sync_with_stdio(false); cin.tie(0);
    26     
    27     cin>>n>>k;
    28     for(int i=1;i<=n;i++)
    29     {
    30         cin>>t.v;
    31         
    32         a[i]=t.v;
    33         t.id=i;
    34         l[i]=i-1;
    35         r[i]=i+1;
    36         que.push(t);
    37     }
    38     r[0]=1;l[n+1]=n;
    39     
    40     while(k--)
    41     {
    42         while(vis[que.top().id]) que.pop();
    43         
    44         t=que.top(); que.pop();
    45         if(t.v<0)break;
    46         
    47         ans+=t.v;
    48         int x=t.id;
    49         a[x]=a[l[x]]+a[r[x]]-a[x];
    50         t.v=a[x];//左右代替为了下次更新
    51         
    52         vis[l[x]]=vis[r[x]]=1;//访问过
    53         
    54         l[x]=l[l[x]];r[l[x]]=x;//修改链表左右指向
    55         r[x]=r[r[x]];l[r[x]]=x;
    56         que.push(t);
    57     }
    58     
    59     cout<<ans<<endl;
    60     
    61     return 0;
    62 }

    完。

  • 相关阅读:
    一、linux 挂起进程 nohup
    1.C#窗体和控件
    C#笔记——5.迭代器
    C#笔记——4.集合
    设计模式——3.观察者模式
    设计模式——2.策略模式
    Code基础——1.数据结构
    设计模式——1.模板方法
    C#笔记——3.泛型
    C#笔记——2.委托
  • 原文地址:https://www.cnblogs.com/redblackk/p/9973181.html
Copyright © 2011-2022 走看看