首页 > 代码库 > 南阳860

南阳860

  1 /*
  2 d[v] = w; ->价值为v时,d[v] = 达到该价值的最小重量
  3 */
  4 #include<iostream>
  5 #include<cstring>
  6 using namespace std;
  7 
  8 int d[10005];
  9 int maxd,n,maxw,w,v;
 10 
 11 void bag(int w,int v)
 12 {
 13     if(w > maxw)
 14         return ;
 15     for(int i=10000; i>v; --i)
 16     {
 17         if( (d[i-v]>0 && d[i-v]+w < d[i]) || (d[i] == 0 && d[i-v]!=0 && d[i-v]+w <= maxw) )
 18         {
 19             d[i] = d[i-v]+w;
 20             if(i > maxd)
 21                 maxd = i;
 22         }
 23     }
 24     if(d[v] > w || d[v] == 0)
 25     {
 26         d[v] = w;
 27         if(v > maxd)
 28             maxd = v;
 29     }
 30 }
 31 
 32 int main()
 33 {
 34     while(cin >> n >> maxw)
 35     {
 36         memset(d,0,sizeof d);
 37         maxd = 0;
 38         while(n--)
 39         {
 40             cin >> w >> v;
 41             bag(w,v);
 42         }
 43         cout << maxd << endl;
 44     }
 45     return 0;
 46 }
 47 
 48 
 49 //最优代码
 50  
 51 #include <cstdio>
 52 #include <cstring>
 53 #include <string>
 54 #include <queue>
 55 #include <algorithm>
 56 #include <vector>
 57 #include <cmath>
 58 #include <iostream>
 59 #include <ctime>
 60 using namespace std;
 61 
 62 const int N = 1e2+10;
 63 const int inf = 1<<30;
 64 int n, W, sumV;
 65 int w[N], v[N];
 66 int dp[N][N*N];
 67 void solve()
 68 {
 69     int i, j;
 70     for(j = 1;j <= sumV;j++)
 71         dp[0][j] = inf;
 72     dp[0][0] = 0;
 73     for(i = 1;i <= n;i++)
 74     {
 75         for(j = 0;j <= sumV;j++)
 76         {
 77             if(j < v[i])
 78                 dp[i][j] = dp[i-1][j];
 79             else
 80                 dp[i][j] = min(dp[i-1][j] , dp[i-1][j-v[i]] + w[i]);
 81         }
 82     }
 83     int res = 0;
 84     for(i = 0;i <= sumV;i++)
 85         if(dp[n][i] <= W)
 86             res = i;
 87     printf("%d\n", res);
 88 }
 89 int main()
 90 {
 91     //freopen("Input.txt","r",stdin);
 92     //freopen("Output.txt","w",stdout);
 93     int i, j;
 94     while(~scanf("%d%d", &n, &W))
 95     {
 96         sumV = 0;
 97         for(i = 1;i <= n;i++)
 98             scanf("%d%d", &w[i], &v[i]), sumV += v[i];
 99         solve();
100     }
101 }
102         

 

南阳860