![复制代码](//assets.cnblogs.com/images/copycode.gif)
#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 100;
int ans = 0;
vector<pair<int, bool> >ret;
void Search(int n, int val, int pos, int tot, vector<pair<int, bool>> &sto) {
if(ans < val) {
ans = val;
ret = sto;
}
// cout << val << endl;
// if(val == 3) {
// for(int i = 0; i < n; i++) {
// cout << i << " " << sto[i].second << endl;
// }
// }
if(tot <= 0)
return ;
int i;
for(i = pos; i < n; i++){
Search(n, val, i + 1, tot, sto);
if(sto[i].first <= tot && !sto[i].second) {
sto[i].second = 1;
Search(n, val + 1, i + 1, tot - sto[i].first, sto);
sto[i].second = 0;
}
}
return ;
}
int main()
{
int n, i, tot_weight;
pair<int, bool> tmp;
printf("总件数为:");
scanf("%d", &n);
// sto.reverse(n + 100);
vector<pair<int, bool> >sto;
for(i = 1; i <= n; i++) {
printf("第%d件物品重量为:", i);
scanf("%d", &tmp.first);
tmp.second = 0;
sto.push_back(tmp);
}
// for(i = 0; i < n; i++) {
// printf("%d %d %d\n", i, sto[i].first, sto[i].second);
// }
printf("船能承受的最大重量为");
scanf("%d", &tot_weight);
Search(n, 0, 0, tot_weight, sto);
printf("在保证效率最大的前提下,能装上船的货物为\n");
for(i = 0; i < n; i++) {
if(!ret[i].second)
continue;
printf("第%d件物品\n", i + 1);
}
return 0;
}
![复制代码](//assets.cnblogs.com/images/copycode.gif)
![](https://img2018.cnblogs.com/common/1586092/201912/1586092-20191222164155653-1115036785.png)
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步