1. Solve the simple loading problem
/*
There are n containers to be loaded on a ship with a deadweight of W, where the weight of container i (1<=i<=n) is wi. Regardless of the volume limitation of the containers, a number of
these containers whose weight sum is less than or equal to W and as large as possible are selected for loading on the ship.
*/
#include<stdio.h>
#include<string.h>
#define MAXN 50
int W;//载重量为W
int n;//n个集装箱
int w[MAXN];
int X[MAXN];//存放最优解
int maxw=0;
void dfs(int i,int tw,int rw,int op[]);
void output();
//i表示第i个集装箱,tw表示选择的集装箱的重量和,rw表示剩余集装箱的重量和
//op表示一个方案
int main()
{
int i;
int s=0;
int op[MAXN];
memset(op,0,sizeof(op));
// printf("请输入轮船的载重量:");
scanf("%d",&W);
// printf("请输入集装箱的数量:");
scanf("%d",&n);
// printf("请输入各个集装箱的重量:");
for(i=1;i<=n;i++){
scanf("%d",&w[i]);
s=s+w[i];
}
dfs(1,0,s,op);
output();
return 0;
}
void dfs(int i,int tw,int rw,int op[])
{
int j;
if(i>n){
if(tw>maxw){
maxw=tw;
for(j=1;j<=n;j++)
X[j]=op[j];
}
}
else{
if(tw+w[i]<=W){
op[i]=1;
dfs(i+1,tw+w[i],rw-w[i],op);
}
if(rw+tw-w[i]>maxw){
op[i]=0;
dfs(i+1,tw,rw-w[i],op);
}
}
}
void output()
{
int i;
int s=0;
// printf("最优方案为:");
for(i=1;i<=n;i++){
if(X[i]==1){
printf("%d ",i);
s=s+w[i];
}
}
printf("\n");
// printf("最优方案的总重量为:");
printf("%d",s);
}
/*
Solve the complex loading problem.
There are a batch of n containers to be loaded on two ships with deadweights c1 and c2. The weight of container i is wi,
and w1+w2+w3+…+wn<=c1+c2. The loading issue requires determining whether there is a reasonable loading plan to load these containers on these two ships.
If so, find a loading plan.
*/
#include<iostream>
#define MAXN 100
#define true 1
#define false 0
using namespace std;
int c1,c2;//轮船的载重量
int n;//集装箱的个数
int w[MAXN];//集装箱的重量
int maxw=0;
int x[MAXN];
void dfs(int i,int tw,int rw,int *op);
int solve();
void output();
int main()
{
int op[MAXN];
int s=0;
cout<<"请输入轮船的载重量:";
cin>>c1>>c2;
cout<<"请输入集装箱的个数:";
cin>>n;
cout<<"请输入集装箱的重量:";
for(int i=1;i<=n;i++){
cin>>w[i];
s=s+w[i];
}
dfs(1,0,s,op);//将第一艘轮船尽可能装满
if(solve()){
cout<<"Yes"<<endl;
output();
}
else cout<<"No";
return 0;
}
void dfs(int i,int tw,int rw,int *op)
{
if(i>n){
if(tw<=c1&&tw>maxw){
maxw=tw;
for(int i=1;i<=n;i++){
x[i]=op[i];
}
}
}
else{
if(tw+w[i]<=c1){
op[i]=1;
dfs(i+1,tw+w[i],rw-w[i],op);
}
if(tw+rw-w[i]>maxw){
op[i]=0;
dfs(i+1,tw,rw-w[i],op);
}
}
}
void output()
{
for(int i=1;i<=n;i++){
if(x[i]==1){
cout<<"将第"<<i<<"个集装箱装上第一艘轮船"<<'\n';
}
else{
cout<<"将第"<<i<<"个集装箱装上第二艘轮船"<<'\n';
}
}
}
int solve()
{
int s=0;
for(int i=0;i<=n;i++){
s=s+w[i];
}
if((s-maxw)>c2)return false;
else return true;
}