1. 程式人生 > >HDU - 5887:Herbs Gathering (map優化超大揹包)

HDU - 5887:Herbs Gathering (map優化超大揹包)

Collecting one's own plants for use as herbal medicines is perhaps one of the most self-empowering things a person can do, as it implies that they have taken the time and effort to learn about the uses and virtues of the plant and how it might benefit them, how to identify it in its native habitat or how to cultivate it in a garden, and how to prepare it as medicine. It also implies that a person has chosen to take responsibility for their own health and well being, rather than entirely surrender that faculty to another. Consider several different herbs. Each of them has a certain time which needs to be gathered, to be prepared and to be processed. Meanwhile a detailed analysis presents scores as evaluations of each herbs. Our time is running out. The only goal is to maximize the sum of scores for herbs which we can get within a limited time.

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 -th line of the following 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\n",ans); } } return 0; }