Codeforces 13C

这题纠结了近半年,一直没有好的思路。

刚开始看这题的时候就是暴力,明显的TLE

后来才知道这题的“一种解”肯定是"原数列中某些数的集合" (很明显这题的最优策略并不唯一)

有原数列 a , 数列 b 是数列 a 的一个有序拷贝(对 a 进行不减排序的结果)

下面就是 dp...

此外这题还需要使用滚动数组,因为内存要求比较高。而且还应使用 long long 或 int64


附代码:


 1 /*
 2     dp, sorting
 3 */
 4 #include <stdio.h>
 5 #include <stdlib.h>
 6 
 7 #define MAX_N (5000 + 5)
 8 #define min(x, y) ((x) < (y) ? (x) : (y))
 9 
10 typedef long long ll;
11 int a[MAX_N], b[MAX_N], n;
12 ll dp[2][MAX_N];
13 
14 int 
15 cmp(const void *x, const void *y) 
16 {
17     return *(int*)x - *(int*)y;
18 }
19 
20 int 
21 main(void)
22 {
23     while (~scanf("%d", &n) && n) {
24         int i, j;
25         for (i = 1; i <= n; i++) { 
26             scanf("%d", a + i);
27             b[i] = a[i];
28         }
29 
30         qsort(b + 1, n, sizeof(int), cmp);
31 
32         dp[0][1] = abs((ll)a[1] - b[1]);
33         for (i = 2; i <= n; i++) {
34             dp[0][i] = min(dp[0][i-1], abs((ll)a[1] - b[i]));
35         }
36         int f = 0;
37         for (i = 2; i <= n; i++) {
38             dp[f^1][1] = dp[f][1] + abs((ll)a[i] - b[1]);
39 
40             for (j = 2; j <= n; j++)
41                 dp[f^1][j] = min(dp[f^1][j-1], dp[f][j] + abs((ll)a[i] - b[j]));
42             f ^= 1;
43         }
44 
45         printf("%lld
", dp[f][n]);
46     }
47 
48     return 0;
49 }
原文地址:https://www.cnblogs.com/Stomach-ache/p/3703256.html