HDU-1258-Sum It Up
http://acm.hdu.edu.cn/showproblem.php?pid=1258
注意每个数只能用一次,且不能出现重复的等式
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int a[20],ans[20];
int sum,n,flag;
void dfs(int x,int count,int m)
{
int i,last;
if(m>sum)
return;
if(m==sum)
{
flag=1;
for(i=1;i<count;i++)
{
if(i==count-1)
printf("%d\n",ans[i]);
else
printf("%d+",ans[i]);
}
}
last=-1;
for(i=x;i<=n;i++)
{
if(last!=a[i])
{
ans[count]=a[i];
last=a[i];
dfs(i+1,count+1,m+a[i]);
}
}
return;
}
int main()
{
int i;
while(scanf("%d%d",&sum,&n),sum||n)
{
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
flag=0;
printf("Sums of %d:\n",sum);
dfs(1,1,0);
if(!flag)
printf("NONE\n");
}
return 0;
}
本文介绍了一个解决HDU-1258-SumItUp问题的算法实现,该问题要求使用一系列给定的整数通过深度优先搜索(DFS)找出所有可能组合中等于指定总和的方案,并避免重复等式。代码采用C语言编写,通过递归调用实现了对所有可能组合的遍历。
410

被折叠的 条评论
为什么被折叠?



