Test instructions: There are a number of numbers that can then be used to cost me a number +i or-I.
Now ask you to put the sequence into a non-ascending or non-descending, asking the minimum price.
Exercises
The first thing that can be proved is that the last number of the best spent can be a number now:
Card: If the two number is adjusted in the middle of the two number, then you can change the two number to one of the number, and the price is obviously equal.
This is good to do after it comes out.
We can discretization, and then f[i][j] that the number of the number of I changes to J 1~i These numbers keep the minimum cost of non-strict monotony
Transfer f[i][j] Do not have to N*n enumeration, you can maintain a prefix optimal (very water), and then O (1) transfer.
Then do the non-liters, once again non-descending solution.
Code:
#include <cmath> #include <cstdio> #include <cstring> #include <iostream> #include < Algorithm> #define N 2500#define inf 0x3f3f3f3f3f3f3f3fllusing namespace std;struct lsh{int X,id;bool operator < (CO NST LSH &a) Const{return x<a.x;}} Lsh[n];int Cnt,n,w[n];long Long F[n][n];int Main () {//freopen ("test.in", "R", stdin); int i,j,k;scanf ("%d", &n); for ( i=1;i<=n;i++) scanf ("%d", &lsh[i].x), Lsh[i].id=i;sort (lsh+1,lsh+n+1), Lsh[0].x=-1;for (i=1;i<=n;i++) {if ( lsh[i].x!=lsh[i-1].x) lsh[++cnt].x=lsh[i].x;w[lsh[i].id]=cnt;} Discretization ends, LSH corresponds to the original value//ascending for (i=1;i<=n;i++) {Long long temp=inf;for (j=0;j<=cnt;j++) {temp=min (temp,f[i-1][j]); F[i] [J]=temp+abs (lsh[w[i]].x-lsh[j].x);}} Long Long ans1=inf;for (i=0;i<=cnt;i++) ans1=min (Ans1,f[n][i]);//Descending for (i=1;i<=n;i++) {Long Long temp=inf;for (j= cnt;j>=0;j--) {temp=min (temp,f[i-1][j]); F[i][j]=temp+abs (lsh[w[i]].x-lsh[j].x);}} Long Long ans2=inf;for (i=0;i<=cnt;i++) ans2=min (Ans2,f[n][i]); Cout<<min (ANS1,ANS2) <<enDl;return 0;}
Copy to Google TranslateTranslation Results
"POJ3666" "Usaco Gold" 2.Cow Game Motion regulation