acm算法基础7 动态规划2

2013 年 6 月 3 日 by sciencefans


今天学习了动态规划中著名的背包问题和最简矩阵连乘步数问题。
两者在实现上都非常相似,都是运用动态规划进行‘打表’,这是动态规划中大多数问题的相同解决过程。然而精髓在于1.如何找到最优子结构并构造转移方程;2.如何打表。
对于前者应该是老生常谈了,后者见得也挺多。举个例子,矩阵连乘问题中,打表就应该以j-i递增的方式递推,而以i, j各自递增的方式就完全不行。
再一点就是,对于动态规划的两类实现方法以后要多练——打表和记忆化搜索。个人倾向于打表,记忆化搜索如果要用到递归则非常容易栈溢出。当然,在伟大的Linux下变态的自动增长栈还是记忆化搜索舒服一些。
附上两题的代码:
1.背包:

 1 #include <stdio.h>
 2 
 3 #include <string.h>
 4 
 5 int result[1005];
 6 
 7 int main()
 8 {
 9 int T;
10 int N,V;
11 int i,j;
12 
13 while(scanf("%d %d",&N,&V)&&(N+V))
14 {
15 int weight[1001],value[1001];
16 
17 for (i=1;i<=N;i++)
18 {
19 scanf("%d",&weight[i]);
20 scanf("%d",&value[i]);
21 }
22 
23 memset(result,0,sizeof(result));
24 for (i=1;i<=N;i++)
25 for(j=V;j>=weight[i];j--)
26 if (result[j-weight[i]]+value[i]>result[j])
27 result[j] = result[j-weight[i]]+value[i];
28 
29 printf("%d\n",result[V]);
30 }
31 
32 return 0;
33 }

 

2.矩阵连乘

 1 //calculate the minimum step to solve the calculation of multiple successive multiplication of matrix
 2 //2013/6/3
 3 //18:36
 4 
 5 #include <stdio.h>
 6 
 7 #define MAX_ROW_X 1000
 8 #define MAX_ROX_Y 1000
 9 #define MAXN 1000
10 #define MAX 32767
11 
12 long long int dp[MAX_ROW_X][MAX_ROX_Y] = {0};
13 long long int x[MAXN] = {0};
14 long long int y[MAXN] = {0};
15 
16 long long int min_mat_mult(void)
17 {
18 long long int n;
19 printf("Input the total number of matrixs: ");
20 scanf("%lld", &n);
21 
22 int i, j, k;
23 for(i = 1; i <= n; i++)
24 {
25 printf("Input the %dth row_x and row_y:\n", i);
26 scanf("%lld%lld", &x[i], &y[i]);
27 if(x[i] < 0 || y[i] < 0 || ( i > 1 && x[i] != y[i - 1]))
28 {
29 printf("Input wrong!\n");
30 return 0;
31 }
32 }
33 
34 for(k = 1; k <= n - 1; k++)
35 {
36 for(i = 1; i <= n - k; i++)
37 {
38 j = i + k;
39 long long int min = MAX;
40 long long int sum = 0;
41 int l;
42 for(l = i; l < j; l++)
43 {
44 sum = dp[i][l] + dp[l + 1][j] + x[i] * y[l] * y[j];
45 if(sum < min)
46 {
47 min = sum;
48 }
49 }
50 dp[i][j] = min;
51 }
52 }
53 return dp[1][n];
54 }
55 
56 int main()
57 {
58 while(1)
59 {
60 long long sum;
61 if(sum = min_mat_mult())
62 printf("\nThe minimum step:%8lld\n", sum);
63 printf("__________________________________________________\n\n");
64 }
65 return 0;
66 }

 

一个简单的半动态规划问题:最大子串和:

 1 #include<stdio.h>
 2 int main()
 3 {
 4 int n,m,i,max,sum;
 5 scanf("%d",&n);
 6 while(n--)
 7 {
 8 max=0;
 9 scanf("%d",&m);
10 scanf("%d",&sum);
11 max=sum;
12 while(--m)
13 {
14 scanf("%d",&i);
15 if(sum<0) sum=i;
16 else sum+=i;
17 if(sum>max) max=sum;
18 }
19 printf("%d\n",max);
20 }
21 }

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值