Topic Link: Click to open the link
Test instructions: To the number of N, it is required to turn this sequence into a non-decrement or non-increment sequence, to minimize the sum of the variable.
Idea: You can design DP, D[I][J] to indicate that the number of I becomes the optimal solution for J, so that it shifts to d[i-1][k], where k<=j, which is turned up, at the cost of ABS (A[i]-j). But the number is too big, and because each number will certainly become a number of these numbers will be optimal, so we might as well discretization the n number first, so that the state is expressed as d[i][j], the number of the number of I into the first J small, transferred to D[i-1][k], where k<=j. But this is still time-out, because it is a triple loop, and found that each time is to take the previous layer of the current minimum value, so it is easy to optimize the 3rd layer off.
See the code for details:
#include <cstdio> #include <cstring> #include <algorithm> #include <iostream> #include < string> #include <vector> #include <stack> #include <bitset> #include <cstdlib> #include < cmath> #include <set> #include <list> #include <deque> #include <map> #include <queue># Define MAX (a) > (b)? ( A):(B) #define MIN (a) < (b) ( A):(B)) using namespace Std;typedef long Long ll;const double PI = ACOs ( -1.0); const double EPS = 1e-6;const int mod = 10000 00000 + 7;const ll INF = (ll) 2000000000000;const int maxn = + 10;int T,n,m,a[maxn],b[maxn],vis[maxn][maxn],kase=0;ll D[maxn][maxn];int Main () {while (~SCANF ("%d", &n)} {for (int i=1;i<=n;i++) {scanf ("%d", &a[ I]); B[i] = A[i]; } sort (b + 1, B + n + 1); for (int i=1;i<=n;i++) for (int j=1;j<=n;j++) d[i][j] = INF; for (int i=1;i<=n;i++) d[1][i] = ABS (A[1]-b[i]); ll ans = INF; FoR (int i=2;i<=n;i++) {ll last = INF; for (int. j=1;j<=n;j++) {last = min (last, d[i-1][j]); D[i][j] = min (D[i][j], last + ABS (a[i)-b[j]); if (i = = N) ans = min (ans, d[i][j]); }} printf ("%i64d\n", ans); } return 0;}
POJ 3666 Making the Grade (DP)