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

    /*对容量为c的背包进行装载。从n个物品中选取装入背包的物品,每件物品i的重量为wi ,价值为pi 。
    对于可行的背包装载,背包中物品的总重量不能超过背包的容量,最佳装载是指所装入的物品价值最高。
    Input
    多个测例,每个测例的输入占三行。
    第一行两个整数:n(n<=10)和c,第二行n个整数分别是w1到wn,第三行n个整数分别是p1到pn。
    n 和 c 都等于零标志输入结束。
    Output
    每个测例的输出占一行,输出一个整数,即最佳装载的总价值。

    Sample Input
    1 2
    1
    1

    2 3   n  bag
    2 2   weight
    3 4   value

    0 0
    Output
    1
    4
    */


    #include<iostream>
    using namespace std;
    int weight[1001],val[1001];
    int a[1000];
    int bag;

    int fun(int n)
    {
      memset(a,0,sizeof(a));
      for(int i=0;i<n;i++){    //n件物品              i=0  
        for(int j=bag;j>=weight[i];j--){         //     bag=3; weight[0]=2; value[0]=3; j=3-2
          if(a[j]<a[j-weight[i]]+val[i])   //   a[3]=a[1]+3=3;  a[2]=3;  
            a[j]=a[j-weight[i]]+val[i];   //    i=1
        }                        //          bag=3;weight[1]=2;value[1]=4; j=3-2
      }                                //           a[3]<a[1]+4=4; a[2]=4;    
      return a[n];
    }

    int main()
    {
      int n;
      while(cin>>n>>bag && (n!=0 || bag!=0)){
        for(int i=0;i<n;i++)    cin>>weight[i];
        for(int i=0;i<n;i++)    cin>>val[i];
        cout<<fun(n)<<endl;;    
      }
      return 0;
    }

  • 相关阅读:
    用wamp配置的环境,想用CMD连接mysql怎么连
    Mysql删除表
    MySQL创建表
    Leetcode 130. Surrounded Regions
    Leetcode 111. Minimum Depth of Binary Tree
    Leetcode 110. Balanced Binary Tree
    Leetcode 98. Validate Binary Search Tree
    Leetcode 99. Recover Binary Search Tree
    Leetcode 108. Convert Sorted Array to Binary Search Tree
    Leetcode 105. Construct Binary Tree from Preorder and Inorder Traversal
  • 原文地址:https://www.cnblogs.com/tinyork/p/3393491.html
Copyright © 2011-2022 走看看