回溯法
来源:互联网 发布:string.h 51单片机 编辑:程序博客网 时间:2024/06/03 05:19
#include <iostream>
using namespace std;
int cw=0;
int cp=0;
int bestc=-9999;
int c;
int n;
struct op
{
int w;
int v;
int d;
}yu[100];
op ty[100];
int Bound(int i)
{
int cleft=c-cw;
int b=cp;
while(i<=n&&ty[i].w<=cleft)
{
cleft=cleft-ty[i].w;
b=b+ty[i].v;
i++;
}
if(i<=n)
{
b+=ty[i].v*cleft/ty[i].w;
}
return b;
}
void backtack(int i)
{
if(i>n)
{
if(bestc<cp)
{
bestc=cp;
}
return ;
}
if(cw+ty[i].w<=c)
{
cw=cw+ty[i].w;
cp=cp+ty[i].v;
backtack(i+1);
cw=cw-ty[i].w;
cp=cp-ty[i].v;
}
if(Bound(i+1)>bestc)
{
backtack(i+1);
}
}
void sort1(op yu[100],int m)
{
op temp;
for(int i=1;i<m;i++)
{
for(int j=i+1;j<=m;j++)
{
if(yu[i].d<yu[j].d)
{
temp=yu[i];
yu[i]=yu[j];
yu[j]=temp;
}
}
}
}
int main()
{
cout<<"请输入物品个数"<<endl;
cin>>n;
cout<<"请输入重量"<<endl;
cin>>c;
for(int i=1;i<=n;i++)
{
cin>>ty[i].w>>ty[i].v;
ty[i].d=ty[i].v/ty[i].w;
}
sort1(ty,n);
backtack(1);
cout<<bestc;
return 0;
}
using namespace std;
int cw=0;
int cp=0;
int bestc=-9999;
int c;
int n;
struct op
{
int w;
int v;
int d;
}yu[100];
op ty[100];
int Bound(int i)
{
int cleft=c-cw;
int b=cp;
while(i<=n&&ty[i].w<=cleft)
{
cleft=cleft-ty[i].w;
b=b+ty[i].v;
i++;
}
if(i<=n)
{
b+=ty[i].v*cleft/ty[i].w;
}
return b;
}
void backtack(int i)
{
if(i>n)
{
if(bestc<cp)
{
bestc=cp;
}
return ;
}
if(cw+ty[i].w<=c)
{
cw=cw+ty[i].w;
cp=cp+ty[i].v;
backtack(i+1);
cw=cw-ty[i].w;
cp=cp-ty[i].v;
}
if(Bound(i+1)>bestc)
{
backtack(i+1);
}
}
void sort1(op yu[100],int m)
{
op temp;
for(int i=1;i<m;i++)
{
for(int j=i+1;j<=m;j++)
{
if(yu[i].d<yu[j].d)
{
temp=yu[i];
yu[i]=yu[j];
yu[j]=temp;
}
}
}
}
int main()
{
cout<<"请输入物品个数"<<endl;
cin>>n;
cout<<"请输入重量"<<endl;
cin>>c;
for(int i=1;i<=n;i++)
{
cin>>ty[i].w>>ty[i].v;
ty[i].d=ty[i].v/ty[i].w;
}
sort1(ty,n);
backtack(1);
cout<<bestc;
return 0;
}
阅读全文
0 0
- 回溯法
- 回溯法
- 回溯法
- 回溯法
- 回溯法
- 回溯法
- 回溯法
- 回溯法
- 回溯法
- 回溯法
- 回溯法
- 回溯法
- 回溯法
- 回溯法
- 回溯法
- 回溯法
- 回溯法
- 回溯法
- vue处理axios post请求传参的问题
- DBus相关问题
- EasyUI按钮控制标签显示与隐藏
- 网络通信
- Oracle:单行函数
- 回溯法
- 《Android 群英传》读书笔记:自定义 View -- 弧线展示图
- UI控件 ->TextField
- 论文笔记:Faster R-CNN: Towards Real-Time Object Detection with Region Proposal Networks
- eclipse+maven搭建web项目
- 大数据(二十七)HBASE【Hbase 综述】
- Linux 文件权限全是问号,无法操作
- 洛谷P2604 [ZJOI2010]网络扩容
- 商城项目总结