题目需要对dp进行优化来减少不需要的空间和时间,在这里我们使用map去保存,使用滚动数组去代替每一种草药。
那么某一种草药对状态的影响就可以表示为去遍历map里面的每一个元素,拿这个元素的时间去加上这个时间,如果满足条件那么就可以去判断这将it->first+t这个时间下的最大值更新掉。
这样可以避免需要不必要的空间。
#include <bits/stdc++.h>
using namespace std;
#define int long long
map<int, int> mp;
signed main() {
ios::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
int n, s;
int t, v;
cin>>n>>s;
mp[0] = 0;
map<int, int>::reverse_iterator it;
while (n--) {
cin>>t>>v;
for (it = mp.rbegin();it!=mp.rend();it++) {
if ((*it).first+t<=s) {
mp[it->first+t]=max(mp[it->first+t],mp[it->first]+v);
}
}
}
int ans = 0;
map<int, int>::iterator itt = mp.begin();
for (itt;itt!=mp.end();itt++) {
ans = max(ans, itt->second);
}
cout<<ans;
return 0;
}

京公网安备 11010502036488号