http://acm.nyist.net/JudgeOnline/problem.php?pid=1058
//AC
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<ctype.h>
#include<stdlib.h>
#include<string>
#include<algorithm>
#include<vector>
#include<set>
#include<map>
#include<list>
#include<queue>
#include<stack>
#include<iomanip>
#include<numeric>
//#include <istream> //基本输入流
//#include <ostream> //基本输出流
//#include <sstream> //基于字符串的流
//#include <utility> //STL 通用模板类
//#include <complex.h> //复数处理
//#include <fenv.h> //浮点环境
//#include <inttypes.h> //整数格式转换
//#include <stdbool.h> //布尔环境
//#include <stdint.h> //整型环境
//#include <tgmath.h> //通用类型数学宏
#define L(a,b,c) for(int a = b;a >= c;a --)
#define M(a,b,c) for(int a = b;a <= c;a ++)
#define N(a,b) memset(a,b,sizeof(a));
#define MAXX(a,b) ((a)>(b)?a:b)
#define MINN(a,b) ((a)<(b)?a:b)
const int MAX=1<<30;
const int MIN=-MAX;
using namespace std;
int n,k,sum,a[100],b[100];
bool ok=false;
void dfs(int m)
{
if(sum==k)
{
if(!ok) //多种情况时,YES只输出一次,对应的数字输出
{
ok=1;
printf("YES\n");
}
M(i,0,n-1)
if(b[i])
{
printf("%d ",a[i]);
}
printf("\n");
}
M(i,m,n-1)
{
sum+=a[i];
b[i]=1;
dfs(i+1);
b[i]=0;
sum-=a[i];
}
}
int main()
{
while(cin>>n>>k)
{
M(i,0,n-1)
cin>>a[i];
sum=0;
dfs(0);
if(!ok)
printf("NO\n");
}
return 0;
}
http://poj.org/problem?id=1564
//粘贴
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
int n,len,a[20],b[20],cnt;
int cmp(int a,int b)
{
return a>b;
}
void dfs(int x,int posa,int sum,int posb) //posb统计位数
{
int i;
if(sum>n) //此时停止,进行下次
return;
if(sum == n) //输出
{
cnt++;
for(i = 0; i<posb; i++)
{
if(i)
printf("+%d",b[i]);
else
printf("%d",b[i]);
}
printf("\n");
}
for(i = posa; i<len; i++)
{
b[posb] = a[i];
dfs(a[i],i+1,sum+a[i],posb+1);
while(i+1<len && a[i] == a[i+1])//搜索完毕后,若下一个搜索的数仍与当前相同,则跳过直至不相同
i++;
}
}
int main()
{
int i;
while(~scanf("%d%d",&n,&len),n+len!=0)
{
for(i = 0; i<len; i++)
scanf("%d",&a[i]);
sort(a,a+len,cmp); //从大到小排序
printf("Sums of %d:\n",n);
cnt = 0;
dfs(0,0,0,0);
if(!cnt) //不存在时
printf("NONE\n");
}
return 0;
}