博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
0-1背包问题 c语言_动态编程在C中的0-1背包问题
阅读量:2510 次
发布时间:2019-05-11

本文共 1803 字,大约阅读时间需要 6 分钟。

0-1背包问题 c语言

Here you will learn about 0-1 knapsack problem in C.

在这里,您将学习C语言中的0-1背包问题。

We are given n items with some weights and corresponding values and a knapsack of capacity W. The items should be placed in the knapsack in such a way that the total value is maximum and total weight should be less than knapsack capacity.

我们给了n个具有一定权重和相应值的项目以及一个容量为W的背包。这些项目应以总值最大且总重量小于背包容量的方式放置在背包中。

In this problem 0-1 means that we can’t put the items in fraction. Either put the complete item or ignore it. Below is the solution for this problem in C using dynamic programming.

在这个问题0-1中,意味着我们不能将项目分成零。 放入完整的项目或忽略它。 下面是使用动态编程在C中解决此问题的方法。

动态编程在C中的背包问题
动态编程的C背包问题程序 (
Program for Knapsack Problem in C Using Dynamic Programming)

#include
int max(int a, int b) { return (a > b)? a : b; } int knapSack(int W, int wt[], int val[], int n){   int i, w;   int K[n+1][W+1];    for (i = 0; i <= n; i++)   {       for (w = 0; w <= W; w++)       {           if (i==0 || w==0)               K[i][w] = 0;           else if (wt[i-1] <= w)                 K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]],  K[i-1][w]);           else                 K[i][w] = K[i-1][w];       }   }    return K[n][W];} int main(){    int i, n, val[20], wt[20], W;        printf("Enter number of items:");    scanf("%d", &n);        printf("Enter value and weight of items:\n");    for(i = 0;i < n; ++i){     scanf("%d%d", &val[i], &wt[i]);    }     printf("Enter size of knapsack:");    scanf("%d", &W);        printf("%d", knapSack(W, wt, val, n));    return 0;}

Output

输出量

Enter number of items:3 Enter value and weight of items: 100 20 50 10 150 30 Enter size of knapsack:50 250

输入物品数量:3 输入物品的重量和重量: 100 20 50 10 150 30 输入背包尺寸:50 250

You can watch below video to learn knapsack problem easily.

您可以观看下面的视频轻松了解背包问题。

Source: 

资料来源: :

翻译自:

0-1背包问题 c语言

转载地址:http://rrggb.baihongyu.com/

你可能感兴趣的文章
eclipse控制台不显示输出的解决办法
查看>>
Java中的TCP/UDP网络通信编程
查看>>
Mysql支持的数据类型(总结)
查看>>
对测试转开发的一些想法
查看>>
MVC文件上传08-使用客户端jQuery-File-Upload插件和服务端Backload组件让每个用户有专属文件夹...
查看>>
html模板中调用变量
查看>>
应用程序缓存的应用(摘抄)
查看>>
C#析构函数,类运行结束后运行
查看>>
在LAMP的生产环境内添加PHP的cURL扩展模块
查看>>
AMH 软件目录介绍
查看>>
你可能使用了Spring最不推荐的注解方式
查看>>
java常见3种文件上传速度对比和文件上传方法详细代码
查看>>
SVD总结
查看>>
python基础教程(三)
查看>>
PL SQL Developer中文乱码
查看>>
字符串知识大全
查看>>
软件目录结构规范及堂兄弟文件引用
查看>>
H5 WebSocket通信和WCF支持WebSocket通信
查看>>
文件上传
查看>>
不能在此路径中使用此配置节。如果在父级别上锁定了该节,便会出现这种情况...
查看>>