首页 > 代码库 > 动态规划求解0-1背包
动态规划求解0-1背包
C代码实现如下:
1 #include <stdio.h> 2 #include <stdlib.h> 3 4 int** DP(int num, int Weight, int*w, int *v); 5 void output(int *c, int *w, int weight, int **ptr, int num); 6 int main() 7 { 8 9 10 int w[] = {3, 4, 7, 8, 9}; 11 int v[] = {4, 5, 10, 11, 13}; 12 int num = 5, weight = 17; 13 int out[5] = {0}; 14 int i = 0, j = 0; 15 int **ptr = NULL; 16 17 ptr = DP(num, weight, w, v); 18 output(out, w, weight, ptr, num); 19 20 for(i = 0; i< num; i++) 21 { 22 for(j = 0; j < weight + 1; j++) 23 { 24 printf("%2d ", ptr[i][j]); 25 } 26 printf("\n"); 27 free(ptr[i]); 28 ptr[i] = NULL; 29 } 30 printf("\n"); 31 free(ptr); 32 ptr = NULL; 33 34 for(i = 0; i < num; i++) 35 { 36 printf("%d ", out[i]); 37 } 38 printf("\n"); 39 system("pause"); 40 return 0; 41 } 42 43 44 int** DP(int num, int Weight, int*w, int *v) 45 { 46 int **arr = (int**)calloc(num, sizeof(int*)); 47 int i = 0, j = 0; 48 for(i = 0; i < num; i++) 49 { 50 arr[i] = (int*)calloc(Weight + 1, sizeof(int)); 51 } 52 53 for(i = 0; i < Weight + 1; i++) 54 { 55 arr[0][i] = 0; 56 } 57 for(i = 0; i < num; i++) 58 { 59 arr[i][0] = 0; 60 for(j = 0; j < Weight + 1; j++) 61 { 62 if(w[i] <= j) 63 { 64 if(i == 0) 65 { 66 arr[i][j] = v[i]; 67 } 68 else 69 { 70 if(v[i] + arr[i - 1][j - w[i]] >= arr[i - 1][j]) 71 { 72 arr[i][j] = v[i] + arr[i-1][j- w[i]]; 73 } 74 else 75 { 76 arr[i][j] = arr[i - 1][j]; 77 } 78 } 79 } 80 else 81 { 82 if(i == 0) 83 { 84 arr[i][j] = 0; 85 } 86 else 87 { 88 arr[i][j] = arr[i - 1][j]; 89 } 90 91 } 92 93 } 94 } 95 96 return arr; 97 } 98 99 void output(int *c, int *w, int weight, int **ptr, int num) 100 { 101 int i = 0; 102 103 for(i = num - 1; i >=1; i--) 104 { 105 if(ptr[i][weight] == ptr[i - 1][weight]) 106 { 107 c[i] = 0; 108 } 109 else 110 { 111 c[i] = 1; 112 weight -= w[i]; 113 } 114 115 116 } 117 118 if(ptr[i][weight] == 0) 119 { 120 c[i] = 0; 121 } 122 else 123 { 124 c[i] = 1; 125 } 126 127 }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。