Title Link: http://poj.org/problem?id=3666
Test instructions: The minimum cost of making a sequence increment or decrement a sequence. The cost is the formula given in the question.
Solution: Dp[i][j] represents the minimum cost of the number of previous I, with Num[j] as the end.
Enumeration J at the time of update
Transfer status:
for (int2; i <= n; i++) { int t = inf; for (int1; j <= n; j++) { min(t,dp[i-1][j]); abs(a[i] - num[j]); } }
Finally, simply traverse DP [n] [K], where k is 1 to N, which represents the minimum cost of using a number in num[1 ~n] as the end of the monotony.
Code:
#include <stdio.h>#include <ctime>#include <math.h>#include <limits.h>#include <complex>#include <string>#include <functional>#include <iterator>#include <algorithm>#include <vector>#include <stack>#include <queue>#include <set>#include <map>#include <list>#include <bitset>#include <sstream>#include <iomanip>#include <fstream>#include <iostream>#include <cmath>#include <cstring>#include <cstdio>#include <time.h>#include <ctype.h>#include <string.h>#include <assert.h>using namespace STD;Const intINF =1e9+7;intNinta[ .], num[ .];intdp[ .][ .];intMain () { while(scanf("%d", &n)! = EOF) { for(inti =1; I <= N; i++) {scanf("%d", &a[i]); Num[i] = A[i]; } sort (num +1, Num +1+ N);memset(DP,0,sizeof(DP)); for(inti =2; I <= N; i++) {intt = INF; for(intj =1; J <= N; J + +) {t = min (t,dp[i-1][J]); DP[I][J] = t +ABS(A[i]-num[j]); } }intans = inf; for(inti =1; I <= N; i++) ans = min (ans,dp[n][i]);printf("%d\n", ans); }return 0;}
Copyright NOTICE: Reprint please indicate the source.
POJ 3666 Making the Grade "DP"