//迭代法解装载问题
#include<stdio.h>
int cw=0,bestw=0;
int r=0;
const maxn=100;
int x[maxn]={0};
int b[maxn]={0};
int n;
int w[maxn];
int c;
void DFS(int t)//执行过程是,先左子树,后右子树,再迭代回溯
{
while(true)
{
while(t<=n&&cw+w[t]<=c)
{
cw+=w[t];
x[t]=1;
r-=w[t];
t++;
}
if(t>n)
{
if(cw>bestw)
{
bestw=cw;
for(int i=1;i<=n;i++)
b[i]=x[i];
}
}
else
{
x[t]=0;
r-=w[t];
t++;
}
while(cw+r<=bestw)//迭代回溯,其实很简单,就是回溯找到这条路径上不为0的那个位置,改变他,就实现了迭代回溯
{
t--;
while(t>0&&x[t]==0)
{
r+=w[t];
t--;
}
if(t==0)
return;//这个return可以跳出最外层的那个while,也就是结束那个true
x[t]=0;
cw-=w[t];
t++;
}
}
}
int main()
{
freopen("input.txt","r",stdin);//这里需要在桌面上建一个input.txt文档,把要求输入的按要求输入即可
freopen("output.txt","w",stdout);
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%d",&w[i]);
r+=w[i];
}
scanf("%d",&c);
DFS(1);
printf("%d\n",bestw);
for(i=1;i<=n;i++)
printf("%d",b[i]);
return 0;
}
#include<stdio.h>
int cw=0,bestw=0;
int r=0;
const maxn=100;
int x[maxn]={0};
int b[maxn]={0};
int n;
int w[maxn];
int c;
void DFS(int t)//执行过程是,先左子树,后右子树,再迭代回溯
{
while(true)
{
while(t<=n&&cw+w[t]<=c)
{
cw+=w[t];
x[t]=1;
r-=w[t];
t++;
}
if(t>n)
{
if(cw>bestw)
{
bestw=cw;
for(int i=1;i<=n;i++)
b[i]=x[i];
}
}
else
{
x[t]=0;
r-=w[t];
t++;
}
while(cw+r<=bestw)//迭代回溯,其实很简单,就是回溯找到这条路径上不为0的那个位置,改变他,就实现了迭代回溯
{
t--;
while(t>0&&x[t]==0)
{
r+=w[t];
t--;
}
if(t==0)
return;//这个return可以跳出最外层的那个while,也就是结束那个true
x[t]=0;
cw-=w[t];
t++;
}
}
}
int main()
{
freopen("input.txt","r",stdin);//这里需要在桌面上建一个input.txt文档,把要求输入的按要求输入即可
freopen("output.txt","w",stdout);
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%d",&w[i]);
r+=w[i];
}
scanf("%d",&c);
DFS(1);
printf("%d\n",bestw);
for(i=1;i<=n;i++)
printf("%d",b[i]);
return 0;
}