标签:std iostream i++ style name ges 价值 stream print
--正文
学到了,原来背包还能这么写
由于最高价值(顶多是五万)很低而重量(10^8)太大,所以反过来找,f[i]为到达价值i所需的最小空间
则 f[i] = min(f[i],f[i-w[i]]+v[i])
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> using namespace std; int f[100000]; int n; int w; int cost[1001],value[1001]; int main(){ while (scanf("%d %d",&n,&w) != EOF){ int i,j; int maxValue = 0; for (i=1;i<=n;i++){ scanf("%d %d",&cost[i],&value[i]); maxValue += value[i]; } for (i=1;i<=maxValue;i++){ f[i] = w+1; } f[0] = 0; int maxj = 0; for (i=1;i<=n;i++){ for (j=maxValue;j>=value[i];j--){ f[j] = min(f[j],f[j-value[i]]+cost[i]); } } int maxi = 1; for (i=1;i<=maxValue;i++){ if (f[i] > w) continue; maxi = i; } printf("%d\n",maxi); } return 0; }
标签:std iostream i++ style name ges 价值 stream print
原文地址:http://www.cnblogs.com/ToTOrz/p/6099917.html