参考书本 背包问题

来源:互联网 发布:数据培训 编辑:程序博客网 时间:2024/04/27 18:10
#define _CRT_SECURE_NO_WARNINGS#include <stdio.h>#include <stdlib.h>int x[100] = { 0 };     //数组X用来存放路径int val[100] = { -1 };//物品单价int weight[100] = { -1 };//存放物品的重量int isOverLoad(int n, int c){int i, w = 0;for (i = 0; i < n; i++)w = w + x[i] * weight[i];if (w>c)return 1;else return 0;}int getVal(int n){int i, v = 0;for (i = 0; i < n; i++)v = v + x[i] * val[i];return v;}void  knap_1(int n, int flag, int c, int *price)//找到物品装包的最高价值量{           //标记0开始  //背包数量   C最大中量   价格int i, j, p;if (isOverLoad(n, c))   //剪纸return;if (n == flag){p = getVal(n);if (*price < p)*price = p;return;}for (i = 0; i <= 1; i++){x[n] = i;knap_1(n + 1, flag, c, price);}}void knap_2(int n, int flag, int c,int price){int i, j, p;if (isOverLoad(n, c))return;if (n == flag){p = getVal(n);if (price == p){printf("---------bag----------\n");for (j = 0; j < n; j++)if (x[j] == 1){printf("|   | p %d:        |   |\n",j);printf("|   |weight:%2d kg|   |\n", weight[j]);printf("|   |price: %2d $ |   |\n\n", val[j]);}printf("----------------------\n\n");getchar();return;}return;}for (i = 0; i <= 1; i++){x[n] = i;knap_2(n + 1, flag, c, price);}}void main2222(){int price = 0, n, c, i;printf("iNPUT THE nmber of products\n");scanf("%d",&n);printf("Input the weight of each product\n");for (i = 0; i < n; i++)scanf("%d",&weight[i]);printf("Input the price of each product\n");for (i = 0; i < n; i++)scanf("%d",&val[i]);printf("Input the limit weight the bag can overload\n");scanf("%d",&c);knap_1(0, n, c, &price);knap_2(0,n,c,price);printf("The grass price : %d $",price);system("pause");}

0 0
原创粉丝点击