首页 > 其他 > 详细

HOJ-1005

时间:2015-10-31 23:01:44      阅读:327      评论:0      收藏:0      [点我收藏+]

这题一看就像是动归,但我就是想不出来怎么动归。。。

纠结了n天之后,果断百度,果然是动归

a[i][j]表示前i个饭店如果需要j个depot

c[i][j]表示如果从第i个到第j个饭店都由一个depot负责,的最短距离

于是就有了神奇的动态转移方程

  a[i][j] = min{a[i][j], a[i-k][j-1]+c[i-k+1][i]} (k = 1, 2, …, i-1)

嗯,然后就益母聊染了

 1 #include<cstdio>
 2 #include<cstdlib>
 3 #include<cstring>
 4 
 5 #define min(a,b) (((a)>(b))?(b):(a))
 6 
 7 #define MAXN 300
 8 
 9 int d[MAXN];//distance between restautants i and headquarter
10 int a[MAXN][MAXN];//the lowest distance while the first i restautants need j depots
11 int c[MAXN][MAXN];//the lowest distance while restautant i to restaurant j need 1 depots
12 
13 int main(void)
14 {
15   int n, k;
16   int num = 1;
17   scanf("%d%d", &n, &k);
18   while(n > 0 && k > 0){
19     for(int i = 1; i <= n; ++i) scanf("%d", &d[i]);
20     memset(c, 0, sizeof(c));
21     for(int i = 1; i <= n; ++i){
22       for(int j = i+1; j <= n; ++j)
23     for(int k = i, p = (i+j)/2; k <= j; ++k)
24       c[i][j] += abs(d[k] - d[p]);
25     }
26     for(int i = 0; i <= n; ++i)
27       for(int j = 0; j <= n; ++j)
28     a[i][j] = 0xFFFFFFF;
29     a[1][1] = 0;
30     for(int i = 2; i <= n; ++i){
31       a[i][1] = c[1][i];
32       for(int j = 2; j <= i && j <= k; ++j)
33     for(int k = 1; k < i; ++k)
34       if(a[i][j] > a[i-k][j-1]+c[i-k+1][i]){
35         a[i][j] = a[i-k][j-1]+c[i-k+1][i];
36         /*for(int i = 0; i < n; ++i) printf("%12d", i);
37         printf("\n");
38         for(int i = 0; i <= n; ++i){
39           printf("%2d: ", i);
40           for(int j = 0; j <= n; ++j) printf("%12d", a[i][j]);
41           printf("\n");
42         }*/
43         //printf("a[%d][%d] = a[%d-%d][%d-1] + c[%d+1][%d]\n", i, j, i, k, j, k, i);
44         //printf("%d = %d + %d\n", a[i][j], a[i-k][j-1], c[k+1][i]);
45       }
46     }
47     printf("Chain %d\n", num++);
48     printf("Total distance sum = %d\n\n", a[n][k]);
49 
50     scanf("%d%d", &n, &k);
51   }
52   return 0;
53 }

 

HOJ-1005

原文:http://www.cnblogs.com/xuezhonghao/p/4926379.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!