zoukankan      html  css  js  c++  java
  • 部分完全背包

    Description:

    部分背包问题是这样一个问题:
     
    给定n种物品和一个背包。物品i的重量是Wi,其价值为Vi,背包的容量为C。应如何选择装入背包的物品,
     
    使得装入背包中物品的总价值最大?
     
    选择物品i装入背包时,可以选择物品i的一部分,而不一定要全部装入背包,1≤i≤n。
     
    例如:背包容量为5,有3个物品
    第一个物品重量是2 价值是3
    第二个物品重量是3 价值是4
    第三个物品重量是4 价值是8
     
    那么选择第三个物品整体和第一个物品的1/2,得到最大总价值9.500
     

    Input:

    多组数据,
    第一行为背包容量W(1<=w<=2000000)和物品数量N(1<N<=200)
    接下来N行每行两个整数分别代表第i个物品的重量wi(wi<=50000)和价值vi(vi<=1000)
    #include<cstdio>
    #include<algorithm>
    using namespace std;
    
    struct Thing{
        double weight,price;//物品的总重量和单位价格
        bool operator<(const Thing &b) const{
            return price>b.price;
        }
    }th[205];
    
    int main(){
        int n;
        double w;
        while(~scanf("%lf%d",&w,&n)){
            for(int i=0;i<n;i++){
                double  value;
                scanf("%lf%lf",&th[i].weight,&value);
                th[i].price=value/th[i].weight;
            }
            sort(th,th+n);
    
            double ans=0;
            int cur=0;//表示现在在考虑第几件物品
            while(w>0&&cur!=n){
                double t=min(w,th[cur].weight);
                //现在背包的大小,第cur件物品剩下的重量
                ans+=t*th[cur++].price;//增加这么多价值,cur到下一件物品
                w-=t;//背包又少了这么多体积
            }
            printf("%.3lf
    ",ans);
        }
        return 0;
    }
  • 相关阅读:
    mac升级后,遇到openssl相关问题
    mysql清空所有表
    composer 管理js css等依赖文件【fxp/composer-asset-plugin】
    php安装pcntl
    git命令
    docker
    OAuth 2.0
    mysql杯观锁与乐观锁
    mysql添加用户,授权,刷新权限
    Mac下安装SecureCRT并激活
  • 原文地址:https://www.cnblogs.com/csustwj/p/4263353.html
Copyright © 2011-2022 走看看