poj 1564 Sum It Up

#include<iostream>        //有重复的深搜剪枝 
using namespace std;

int mount,pre_value,mark;
int a[12][2];
void output()
{
mark
++;
int flag=0;
for(int i=0;i<mount;i++)
{
if(a[i][1])
{
if(flag++) cout<<"+";
cout
<<a[i][0];
}
}
cout
<<endl;
}
void dfs(int sum,int now_value,int pre)
{
if(now_value==sum)
output();
else
for(int j=pre+1;j<mount;j++)
if(now_value+a[j][0]<=sum&&a[j][0]!=pre_value)
{
a[j][
1]=1;
dfs(sum,now_value
+a[j][0],j);
a[j][
1]=0;
}
if(pre!=-1)
pre_value
=a[pre][0];
//a[j][0]!=pre_value,是为了去掉无效的重复搜索,比如输入4 6 4 3 2 2 1 1
//若去掉这句,则会产生两次3+2+1
}
int main()
{
int sum,i;

while(cin>>sum>>mount&&mount)
{
for(i=0;i<mount;i++)
{
cin
>>a[i][0];
a[i][
1]=0;
}

mark
=0;pre_value=0;
cout
<<"Sums of "<<sum<<":"<<endl;
dfs(sum,
0,-1);
if(mark==0)
cout
<<"NONE"<<endl;
}
return 0;
}

  

posted on 2011-07-18 11:24  sysu_mjc  阅读(181)  评论(0编辑  收藏  举报

导航