Subject to the effect:
Topic links: https://www.luogu.org/problemnew/show/P1484
have
points, wherein select adjacent to each other does not exceed
points, so that the right and the maximum point.
Ideas:
Thinking problems.
Consider greedy. If we choose the maximum points for the first time
When, then select two points or points
sum point
election together, or neither of the two.
If we choose to point sum point , then the greedy thoughts, must be greater than any of . But when time, is certainly less than (For a start, is the greatest). contradiction.
QED
If you do not choose
and
, then it is a normal greedy. But if you choose
and
, then it needs to meet revocable.
If we
is changed to the value of
, selected again
array maximum value,
is equal to
!
So used to maintain the maximum heap, it can be done complexity
Code:
#include <queue>
#include <cstdio>
#define mp make_pair
using namespace std;
typedef long long ll;
const int N=500010;
int n,m;
bool p[N];
ll a[N],ans;
priority_queue<pair<ll,int> > q;
struct node
{
int l,r;
}link[N];
int main()
{
scanf("%d%d",&n,&m);
for (int i=1;i<=n;i++)
{
scanf("%lld",&a[i]);
q.push(mp(a[i],i));
link[i].l=i-1; link[i].r=i+1;
}
while (m--)
{
while (p[q.top().second]) q.pop();
if (q.top().first<0) break;
ans+=q.top().first;
int id=q.top().second;
a[id]=a[link[id].l]+a[link[id].r]-a[id];
p[link[id].l]=p[link[id].r]=1;
link[id].l=link[link[id].l].l; link[link[id].l].r=id;
link[id].r=link[link[id].r].r; link[link[id].r].l=id;
q.pop(); q.push(mp(a[id],id));
}
printf("%lld",ans);
return 0;
}