P1484-种树

 1 #include <bits/stdc++.h>
 2 #define _for(i,a,b) for(int i = (a);i < b;i ++)
 3 #define _rep(i,a,b) for(int i = (a);i > b;i --)
 4 #define INF 0x3f3f3f3f
 5 #define MOD 1000000007
 6 #define pb push_back
 7 #define maxn 500003 
 8 typedef long long ll;
 9 using namespace std;
10 inline ll read()
11 {
12     ll ans = 0;
13     char ch = getchar(), last = ' ';
14     while(!isdigit(ch)) last = ch, ch = getchar();
15     while(isdigit(ch)) ans = (ans << 1) + (ans << 3) + ch - '0', ch = getchar();
16     if(last == '-') ans = -ans;
17     return ans;
18 }
19 inline void write(ll x)
20 {
21     if(x < 0) x = -x, putchar('-');
22     if(x >= 10) write(x / 10);
23     putchar(x % 10 + '0');
24 }
25 ll N,K;
26 struct Tree
27 {
28     ll id;
29     ll val;
30 };
31 struct cmp
32 {
33     bool operator() (const Tree a,const Tree b) const
34     {
35         return a.val < b.val;
36     }
37 };
38 priority_queue<Tree,vector<Tree>,cmp> pq;
39 ll a[maxn];
40 ll l[maxn],r[maxn];
41 ll vis[maxn];
42 ll ans = 0;
43 int main()
44 {
45     N = read();
46     K = read();
47     _for(i,1,N+1)
48     {
49         a[i] = read();
50         l[i] = i-1;r[i] = i+1;
51         pq.push({i,a[i]});
52     }
53     
54     _for(i,0,K)
55     {
56         Tree tmp = pq.top();
57         while(vis[tmp.id])
58         {
59             pq.pop();
60             tmp = pq.top();
61         }
62         if(tmp.val<=0)
63             break;
64         pq.pop();
65         ans += tmp.val;
66         pq.push({tmp.id,a[l[tmp.id]]+a[r[tmp.id]]-tmp.val});
67         a[tmp.id] = a[l[tmp.id]]+a[r[tmp.id]]-tmp.val;
68         vis[l[tmp.id]] = vis[r[tmp.id]] = 1;
69         l[tmp.id]=l[l[tmp.id]];r[l[tmp.id]]=tmp.id;
70         r[tmp.id]=r[r[tmp.id]];l[r[tmp.id]]=tmp.id;
71     }
72     write(ans);
73     return 0;
74 }

 

posted @ 2019-09-21 18:46  Asurudo  阅读(151)  评论(0编辑  收藏  举报