Luo Gu: P3817 Little A's candy (greedy,)

topic:

Insert picture description here

Analysis: A very simple greedy, I hope I can calmly analyze in the examination room.

From left to right, when the first pair of sums exceeds x, the one on the right is obviously deleted.

A pit, the minimum is 0.

Code:

#include<bits/stdc++.h>
using namespace std;
int m,x;
int A[100005];
int main()
{
    
    
 cin>>m>>x;
 for(int i=0;i<m;i++) cin>>A[i];
 long long ans=0;
 for(int i=0;i<m-1;i++)
 {
    
    
  if(A[i]+A[i+1]<=x) continue;
  ans+=A[i]+A[i+1]-x;
  int c=A[i]+A[i+1]-x;
  A[i+1]=A[i+1]-c;
  A[i+1]=max(A[i+1],0);
 }
 cout<<ans;
}

Guess you like

Origin blog.csdn.net/weixin_42721412/article/details/108509793