01背包之贪心选择
来源:互联网 发布:魔兽任务数据库 编辑:程序博客网 时间:2024/05/18 00:13
#include <stdio.h>#include <stdlib.h>#define random(x) (rand()%x)+1 //产生随机数 (0,100]#define N 5 //物品规模#define C 60 //背包容量int x[N]; //解向量//背包节点struct Node{ float wv;//单位重量的价值 int weight;//重量 int value;//价值 bool flag;//0表示不装入背包, 1表示装入书包 int no;//编号 [0,+]};//按序排序函数int compare(const void *a,const void *b){return *(float *)a < *(float *)b ? 1 : -1; }//贪心算法void greedy01(Node nodes[],int n,int c){//按照wv排序qsort(nodes,n,sizeof(nodes[0]),compare);//查看排序后printf("(greedy algorithm)按照wv排序后:\n");for(int i=0;i<n;i++){printf("%d%d%d%d%f\n",nodes[i].no,nodes[i].weight,nodes[i].value,nodes[i].flag,nodes[i].wv);}//按序挑选inti=0;while(c>nodes[i].weight){nodes[i].flag=1; //物品的状态设置为装入背包x[nodes[i].no]=1; //修改解向量c=c-nodes[i].weight; //容量减小i++;}}//输出解向量void printx(int x[],int n){printf("解向量x={");for(int i=0;i<n-1;i++){printf("%d,",x[i]);}printf("%d}\n",x[n-1]);}void main(){structNode nodes[N];//用数组初始化物品节点,背包容量为总重量的一半int v[N]={5,4,3,6,8};//价值数组int w[N]={2,1,3,2,4};//重量数组int c=0;printf("noweightvalueflagwv(init)\n");int i;for(i=0;i<N;i++){nodes[i].no=i;nodes[i].weight=w[i];nodes[i].value=v[i];nodes[i].flag=0;nodes[i].wv=(float)nodes[i].value/nodes[i].weight;printf("%d%d%d%d%f\n",nodes[i].no,nodes[i].weight,nodes[i].value,nodes[i].flag,nodes[i].wv);c=c+w[i];}c=c/2;printf("%d\n",c);greedy01(nodes,N,c);printx(x,N);}
0 0
- 01背包之贪心选择
- 证明01分数背包问题具有贪心选择性质
- 贪心之背包问题
- 贪心之背包问题
- 贪心之活动选择
- hdu2159(贪心+01背包)
- UVALive3637(01背包+贪心)
- 饭卡 01背包 + 贪心
- 背包问题之贪心学习
- 贪心法之背包问题
- 贪心算法之背包问题
- 贪心算法之背包问题
- 贪心算法之背包问题
- 整体贪心 + 局部01背包 之 hdu 2546
- 贪心算法之活动选择
- 贪心之活动选择问题
- 贪心之活动选择问题
- 贪心之活动选择问题
- Ubuntu 16.04 LTS (LEMP) 安装 Nginx/PHP 7/MySQL 5.7
- Struts1入门
- 设备驱动中的inode(kernel-4.7)
- codeforces 9C 数位DP做法
- 【BZOJ 3123】[Sdoi2013]森林 启发式合并主席树
- 01背包之贪心选择
- 怎么使用easy_ui搭建后台ui--初试牛刀(下)管理页面的搭建以及数据的增删查改实现
- Python与机器学习1
- MFC使窗口弹出时显示在屏幕中间或屏幕左上角
- gdb调试技巧
- spring源码学习 - 注解bean的初始化过程
- 基于android的家庭收支管理软件
- Python爬虫基础细节(urllib+cookielib+BeautifulSoup)
- 解决IIS下UTF-8文件报错乱码的问题