[Luogu P2893] [USACO08FEB] Osamuro Making the Grade

Seeking the meaning of the title is a sequence substantially changed monotonically increasing or monotonically decreasing minimum cost, the cost is the difference between the height of the front to change the absolute value of the change. Then do it directly with dp. We dp [i] [j] i represents the front section to maintain an orderly, paragraph i height is h [j] the minimum cost. Because no matter how we change, in fact, the height of the change always occurs between the original sequence, because obviously change a value that must change its left and right sides of the smaller flush. So we get a highly discrete array h. Clearly then transfer equation is:

dp[i][j] = min(dp[i][k]) + abs(a[i] - h[j]);

And if we direct violence enumerate all of k, complexity of the n- 3 , will obviously explode. Consider optimization. In fact, we do not have to enumerate k, can be determined when the minimum dp directly previous transfer [i] [k], the code details see:

#include<cstdio>
#include<iostream>
#include<cmath>
#include<cstring>
#include<string>
#include<algorithm>
#include<cstdlib>
#include<ctime>
#include<queue>
#include<stack>
#include<vector>
#include<set>
#include<map>
#include<deque>
#define ll long long
#define N 2010
using namespace std;
int n,cnt;
int dp[N][N];
int a[N],h[N];
int main()
{
    scanf("%d",&n);
    for(int i = 1;i <= n;i++)
    {
        scanf("%d",&a[i]);
        h[i] = a[i];
    }
    sort(h + 1,h + n + 1);
    int ans = 100000000;
    for(int i = 1;i <= n;i++) 
    {
        for ( int J = . 1 ; J <= n-; J ++ ) 
        { 
            IF (J == . 1 ) DP [I] [J] = DP [I - . 1 ] [J] + ABS (A [I] - H [J ]); // set dp [i] [1] is minimized 
            the else DP [I] [J] = min (DP [I] [J - . 1 ], DP [I - . 1 ] [J] + ABS (a [I] - H [J])); // this step is to determine the minimum DP [I] [J] 
            IF (== n-I) ANS = min (DP [I] [J], ANS); / / final tally answer 
        } 
    } 
    printf ( " % d " , ANS);
      return  0 ; 
}

 

Guess you like

Origin www.cnblogs.com/lijilai-oi/p/10991660.html