Making the Grade
Time Limit : 2000/1000ms (Java/Other) Memory Limit : 131072/65536K (Java/Other)
Total Submission(s) : 1 Accepted Submission(s) : 1
A straight dirt road connects two fields on FJ's farm, but it changes elevation more than FJ would like. His cows do not mind climbing up or down a single slope, but they are not fond of an alternating succession of hills and valleys. FJ would like to add and remove dirt from the road so that it becomes one monotonic slope (either sloping up or down).
You are given N integers A1, ... , AN (1 ≤ N ≤ 2,000) describing the elevation (0 ≤ Ai ≤ 1,000,000,000) at each of N equally-spaced positions along the road, starting at the first field and ending at the other. FJ would like to adjust these elevations to a new sequence B1, . ... , BN that is either nonincreasing or nondecreasing. Since it costs the same amount of money to add or remove dirt at any position along the road, the total cost of modifying the road is
|A1 - B1| + |A2 - B2| + ... + |AN - BN |
Please compute the minimum cost of grading his road so it becomes a continuous slope. FJ happily informs you that signed 32-bit integers can certainly be used to compute the answer.
对于这个引理,简单地证明一下:
可以用数学归纳法证明。
假设b[1~k-1]都在a[]中出现过;
对于b[k],若a[k]>b[k-1],则b[k]=a[k]解最优;
若a[k]<b[k-1],则一定存在t,使b[t~k]变为a[k]的最优解;
或b[k]=b[k-1];
特殊地,对于1号位置,b[1]=a[1]必定为最优解。
综上,引理显然得证。
接下来进行dp
我们令dp[i][j]来表示前i个数中形成单调序列并且最后一个为j的 最小花费;那么因为最后一个数为j,所以之前的数必须小于j,所以(i,j)的花费 为min{dp[i][k]}+j-a[i];
所以状态转移方程为 dp[i][j]=min{dp[i][k]}+j-a[i];
还不知道怎么推
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<algorithm> 5 #include<cmath> 6 #define inf 0x3f3f3f3f; 7 using namespace std; 8 int n; 9 int a[2010], num[2010], f[2010][2010]; 10 int main() 11 { 12 scanf("%d", &n); 13 for (int i = 1; i <= n; i++) 14 { 15 scanf("%d", &a[i]); 16 num[i] = a[i]; 17 } 18 sort(num + 1, num + n + 1); 19 memset(f,0x3f3f3f3f, sizeof(f)); 20 f[0][0] = 0; 21 int tmp = 0; 22 int i, j; 23 for (i = 1; i <= n; i++) 24 { 25 tmp = f[i-1][0]; 26 for (j = 1; j <= n; j++) 27 { 28 tmp = min(tmp, f[i - 1][j]); 29 f[i][j] = abs(num[j] - a[i]) + tmp; 30 } 31 } 32 int ans = inf; 33 for (i = 1; i <= n; i++) 34 { 35 ans = min(ans, f[n][i]); 36 } 37 printf("%d ", ans); 38 return 0; 39 }