HDU - 5887:Herbs Gathering (map優化超大揹包)
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
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> #definell 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\n",ans); } } return 0; }