InputThere are at most ten test cases.
For each case, the first line consists two integers, the total number of different herbs and the time limit.
The i i
-th line of the following n n
line consists two non-negative integers. The first one is the time we need to gather and prepare the i i
-th herb, and the second one is its score.
The total number of different herbs should be no more than 100 100
. All of the other numbers read in are uniform random and should not be more than 10 9 109
.OutputFor each test case, output an integer as the maximum sum of scores.Sample Input
3 70 71 100 69 1 1 2
Sample Output
3
题意:N个物品,以及定容量为M的容器,每个物品有自己的体积和价值,求最大价值。
思路:就是01背包,但是M过大,每个物体的体积也是,我们我们需要优化空间。 这里用map,每次做完01背包后,去掉体积变大,价值没有变大的部分。
好像还可以用搜索做,但是我举得没有这个巧妙。
对于map,我们用iterator来遍历的时候,其实是按下标从小到大遍历的,与插入的顺序无关。 但如果是unordered_map,那么就与插入的顺序无关,所以这个题不能用后者。
#include<bits/stdc++.h> #define ll long long using namespace std; map<int,ll>mp,tmp; map<int,ll>::iterator it; int main() { int N,M,v,w; ll ans; while(~scanf("%d%d",&N,&M)){ mp.clear(); mp[0]=0; for(int i=1;i<=N;i++){ scanf("%d%d",&v,&w); tmp.clear(); for(it=mp.begin();it!=mp.end();it++){ int x=it->first;ll y=it->second; if(tmp.find(x)==tmp.end()) tmp[x]=y; else tmp[x]=max(tmp[x],y); if(x+v<=M) tmp[x+v]=max(tmp[x+v],y+w); } mp.clear(); ll ans=-1; for(it=tmp.begin();it!=tmp.end();it++) if(it->second>ans){ mp[it->first]=it->second; ans=it->second; } if(i==N) printf("%lld ",ans); } } return 0; }