标签:des style class blog code http
题目链接:
http://poj.org/problem?id=1564
题目:
| Time Limit: 1000MS | Memory Limit: 10000K | |
| Total Submissions: 5839 | Accepted: 2984 |
Description
Input
Output
Sample Input
4 6 4 3 2 2 1 1 5 3 2 1 1 400 12 50 50 50 50 50 50 25 25 25 25 25 25 0 0
Sample Output
Sums of 4: 4 3+1 2+2 2+1+1 Sums of 5: NONE Sums of 400: 50+50+50+50+50+50+25+25+25+25 50+50+50+50+50+25+25+25+25+25+25
Source
这个题目是典型的dfs。。
我觉得主要的就是重复的数字不需要进行搜索了,因为已经搜索过了,否则会重复。。
当不满足条件时返回上一臣调用处。。
所以代码为:
#include<cstdio>
#include<cstdlib>
const int maxn=100+10;
int a[maxn],b[maxn];
int t,n,ok;
void dfs(int i,int j,int sum)
{
int k;
if(sum>t)
return;
if(sum==t)
{
printf("%d",b[1]);
for(k=2;k<j;k++)
printf("+%d",b[k]);
printf("\n");
ok=1;
return;
}
for(k=i;k<=n;k++)
{
b[j]=a[k];
dfs(k+1,j+1,sum+a[k]);
while(a[k]==a[k+1])
k++;
}
}
int main()
{
int sum;
while(scanf("%d%d",&t,&n)!=EOF)
{
if(t==0&&n==0) return 0;
sum=0;
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
sum=sum+a[i];
}
printf("Sums of %d:\n",t);
ok=0;
if(sum<t)
{
printf("NONE\n");
continue;
}
else
dfs(1,1,0);
if(!ok)
printf("NONE\n");
}
return 0;
}
poj1564 Sum it up,布布扣,bubuko.com
标签:des style class blog code http
原文地址:http://blog.csdn.net/u014303647/article/details/32750227