Main topic:
Given a sequence, it becomes a monotone or monotone non-decreasing sequence at the minimum cost, and the minimum change value is obtained; a discretized DP is required.
State transition equation:
Dp[i][j]=abs (J-w[i]) +min (dp[i-1][k]);(k<=j) Here K does not need to traverse from 1 to J.
As long as a dp[i-1][j] minimum value mn=min (Mn,dp[i-1][j]) is constantly updated when J is in the For loop,
Then to Dp[i][j]=abs (J-w[i]) +mn can be;
1#include <algorithm>2#include <iostream>3#include <cstdio>4#include <cstring>5#include <cmath>6 using namespacestd;7 Const intN =550;8 Const intMAX =0x3fffffff;9 Long LongDp[n][n];Ten intA[n],b[n],n; One intcmpintXinty) A { - if(x>y)return 1; - return 0; the } - Long LongSolve () - { - for(intI=1; i<=n; i++) + { - Long LongMN = dp[i-1][1]; + for(intK =1; k<=n; k++) A { atmn = min (mn,dp[i-1][k]); -DP[I][K] = ABS (A[i]-b[k]) +mn; - } - } - Long LongAns = dp[n][1]; - for(inti =1; i<=n; i++) in { -Ans =min (ans,dp[n][i]); to } + returnans; - } the intMain () * { $ intT;Panax Notoginsengscanf"%d\n",&t);//poj This place is not a T-group data, you need to change the input - while(t--) the { +scanf"%d",&n); A for(inti =1; i<=n; i++) the { +scanf"%d",&a[i]); -B[i] =A[i]; $ } $Sort (b +1, b+n+1); - Long LongANS1 = Solve ();//One increment sequence -Sort (b +1, B +1+n,cmp); the Long LongAns2 = Solve ();//To find the minimum value of a descending sequence - Long Longans=min (ans1,ans2);Wuyiprintf"%lld\n", ans); the } - return 0; Wu}
POJ 3666 Henan Province seventh session programming D (Mountain Road)