每日打卡 还剩93道题
作者:
__NULL__
,
2024-08-10 10:22:19
,
所有人可见
,
阅读 106
背包问题求具体方案
#include<bits/stdc++.h>
using namespace std;
const int MAXX = 1e5 + 5;
int n, v, a[MAXX], b[MAXX], dp[MAXX];
vector<int> e[MAXX];
bool minn(int x, int y, int z){
vector<int> num = e[y];
num.push_back(z);
for(int i = 0; i < max(num.size(), e[x].size()); i++){
if(i == num.size()){
return 0;
}else if(i == e[x].size()){
return 1;
}
if(num[i] != e[x][i]){
return num[i] < e[x][i];
}
}
}
int main(){
cin >> n >> v;
for(int i = 1; i <= n; i++){
cin >> a[i] >> b[i];
}
for(int i = 1; i <= n; i++){
for(int j = v; j >= a[i]; j--){
if(dp[j] < dp[j - a[i]] + b[i]){
dp[j] = max(dp[j - a[i]] + b[i], dp[j]);
e[j] = e[j - a[i]];
e[j].push_back(i);
}else if(dp[j] == dp[j - a[i]] + b[i]){
if(minn(j, j - a[i], i)){
e[j] = e[j - a[i]];
e[j].push_back(i);
}
}
}
}
for(int i = 0; i < e[v].size(); i++){
cout << e[v][i] << " ";
}
return 0;
}