CF484D (greedy + DP)

Bad practice:

This problem using greedy: points out of the range must be monotonous, because if not monotonous can split out the answer more monotonous. Consider an extreme value when transferring ownership DP

#include<queue>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<cmath>
using namespace std;
typedef long long ll;
const int maxm=1e6+7;
int n;
ll a[maxm];
ll f[maxm];
bool check(int x)//确立极值 
{
 if(a[x]>=a[x-1]&&a[x]>=a[x+1]) return 1;
 else if(a[x]<=a[x-1]&&a[x]<=a[x+1]) return 1;
 return 0;  
}
int main()
{
 scanf("%d",&n);
 for(int i=1;i<=n;i++)
 scanf("%lld",a+i);
 f[1]=0;
 int l=1;
 for(int i=2;i<=n;i++)
 {
   f[i]=max(f[l]+abs(a[i]-a[l+1]),f[l-1]+abs(a[l]-a[i]));
   if(check(i)) l=i;
 }
 printf("%lld\n",f[n]);
 return 0;  
}

Guess you like

Origin www.cnblogs.com/lihan123/p/11794470.html