[算法导论] 15.1 动态规划初步 装配链c语言实现

动态规划的基本特征 //TODO

动态规划的基本步骤 //TODO


装配链的DP实现:

#include <stdio.h>
#define N 100

void DP();
void init();
void printLine();
void printL(int *, int);

void printA(int a[3][N], int n, int m);

int n,
	e1, e2, 
	x1, x2,
	a[3][N] = {
		{0, 0, 0, 0, 0, 0, 0},
		{0, 7, 9, 3, 4, 8, 4},
		{0, 8, 5, 6, 4, 5, 7}
	},
	t[3][N] = {
		{0},
		{0, 2, 3, 1, 3, 4, 0},
		{0, 2, 1, 2, 2, 1, 0}
	},
	f1[N] = {0}, f2[N] = {0}, 
	l1[N] = {0}, l2[N] = {0}, 
	f,ln;

int main(){
	init();
	DP();
	printL(f1, n);
	printL(f2, n);
	printLine();
	return 0;
}

void init(){
	e1 = 2;
	e2 = 4;
	x1 = 3;
	x2 = 2;
	n = 6;
}

void DP(){
	f1[1] = e1 + a[1][1];
	f2[1] = e2 + a[2][1];
	
	register j;
	
	/* do the dp */
	for( j = 2; j <= n; j++){
		/* computer f1 */
		if( (f1[j - 1] + a[1][j]) <= (f2[j - 1] + t[2][j - 1] + a[1][j])){
			f1[j] = f1[j - 1] + a[1][j];
			l1[j] = 1;
		}else{
			f1[j] = f2[j - 1] + t[2][j - 1] + a[1][j];
			l1[j] = 2;
		}
		
		/* computer f2 */
		if( (f2[j - 1] + a[2][j]) <= (f1[j - 1] + t[1][j - 1] + a[2][j])){
			f2[j] = f2[j - 1] + a[2][j];
			l2[j] = 2;
		}else{
			f2[j] = f1[j - 1] + t[1][j - 1] + a[2][j];
			l2[j] = 1;
		}
	}

	if((f1[n] + x1) <= (f2[n] + x2)){
		f = f1[n] + x1;
		ln = 1;
	}else{
		f = f2[n] + x2;
		ln = 2;
	}
}

void printLine(){
	int line = ln, j;
	printf("Line %d, station %d \n", line, n);

	for(j = n; j >= 2; j--){
		line = (line == 1) ? l1[j] : l2[j]; 
		printf("Line %d, station %d\n",line , j - 1);
	}

	printf("the min time is f = %d\n", f);
}

void printL(int *l, int n){
	int i;

	for(i = 1; i <= n; i++){
		printf("f[%d] = {%d}\n",i, l[i] );
	}
}

void printA( int a[3][N], int n, int m ){
	int i, j;

	/* 0 not used */
	for( i = 1; i < n; i++){
		for(j = 1; j <= m; j++){
			printf("a[%d][%d] = {%d}\n", i, j, a[i][j]);
		}
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值