zoukankan      html  css  js  c++  java
  • 背包问题

    代码一:

    //背包问题
    #include<iostream>
    #include<vector>
    #include<algorithm>
    using namespace std;
    struct node{
        double w;
        double p;
        double t;
    };
    
    int cmp(const node &a,const node &b){
        return a.t>b.t;
    }
    
    int main(){
        vector<node> str;
        double weight,price=0;
        double wei=0;
        node b;
        int n;
        while(cin>>n>>weight){
            for(int i=0;i<n;i++)
            {
                cin>>b.p>>b.w;
                b.t=b.p/b.w;
                str.push_back(b);
            }
            sort(str.begin(),str.end(),cmp);
            vector<node>::iterator it;
    //        for(it=str.begin();it!=str.end();it++)  cout<<(*it).p<<" "<<(*it).w<<endl;
            for(it=str.begin();it!=str.end();it++){
            if(wei+(*it).w<=weight) {
                wei+=(*it).w;
                price+=(*it).p;
            }     
            }
            cout<<price<<endl;
        }
    }
    View Code

    测试数据:结果为220

    5
    50
    60 10
    100 20
    120 30
    30 10
    40 20
    View Code

    代码二:结果为240

    //背包问题
    #include<iostream>
    #include<vector>
    #include<algorithm>
    using namespace std;
    struct node{
        double w;
        double p;
        double t;
    };
    
    int cmp(const node &a,const node &b){
        return a.t>b.t;
    }
    
    int main(){
        vector<node> str;
        double weight,price=0;
        double wei=0;
        node b;
        int n;
        while(cin>>n>>weight){
            for(int i=0;i<n;i++)
            {
                cin>>b.p>>b.w;
                b.t=b.p/b.w;
                str.push_back(b);
            }
            sort(str.begin(),str.end(),cmp);
            vector<node>::iterator it;
    //        for(it=str.begin();it!=str.end();it++)  cout<<(*it).p<<" "<<(*it).w<<endl;
            for(it=str.begin();it!=str.end();it++){
                if(wei>=weight) break;
            if(wei+(*it).w<=weight) {
                wei+=(*it).w;
                price+=(*it).p;
            }     else {
                price+=(*it).p*(weight-wei)/(*it).w;
                wei=weight;
            }
            }
            cout<<price<<endl;
        }
    }
    View Code
  • 相关阅读:
    打包和调试静态库(2)
    打包和调试静态库(1)
    Xcode7--免证书真机调试
    开发者账号申请附录
    AFN3.0封装
    MPMoviePlayerController属性,方法,通知整理
    排序算法03--选择排序
    排序算法02--冒泡排序
    遇到别人留下的storyboard的,你需要一个引导图,但是不知道怎么跳转.
    将UIview描画成虚线等.
  • 原文地址:https://www.cnblogs.com/helloworld2019/p/10357538.html
Copyright © 2011-2022 走看看