题目大意:
现有多个测例,每个测例中给定一个和t(t < 1000),和n个非增排列的正整数(1 ≤ n ≤ 12,正整数都小于100),中间可能有重复的数,现要求出用给定的这n个数凑出t有多少种可能,并输出所有不同的可能,比如4 6 4 3 2 2 1 1,其中t = 4,n = 6,序列为4 3 2 2 1 1,其中共有4 = 4, 3 + 1, 2 + 2, 2 + 1 + 1这4种不同的可能,并以+表达式输出所有结果,其中输入保证序列是非增的,并且要求输出序列也是非增的,同时不同可能按照"字典序降序"排列,比如对于两序列,如果两者的第一个数不同,则较大拥有较大数的那个序列排在前面输出,如果第一个数相同则比较第二个数,一次类推,如果误解则输出"NONE",测例以n = 0表示结束。
注释代码:
/*
* Problem ID : POJ 1564 Sum It Up
* Author : Lirx.t.Una
* Language : C++
* Run Time : 0 ms
* Run Memory : 132 KB
*/
#include <iostream>
#include <cstdio>
//序列的最大长度
#define MAXN 12
int n;//序列的长度
int stp;//当前搜索的深度
bool res;//表示是否搜索成功
int a[MAXN];//array,存放序列
int path[MAXN];//存放最终的结果序列,序列中值相加等于t
bool
dfs( int lft, int i ) {//left,表示剩余多少就能凑到t了
//i表示当前搜索到序列第i号数
int j;//计数变量
if ( !lft ) {//表示已经凑出t了,可以直接输出结果
printf("%d", *path);
for ( j = 1; j < stp; j++ ) printf("+%d", path[j]);
putchar('\n');
return true;//搜索成功
}
for ( ; i < n; i++ )//从前往后搜(也是从大到小搜)
if ( a[i] <= lft ) {//碰到可行的就试一下
path[stp++] = a[i];
if ( dfs( lft - a[i], i + 1 ) ) res = true;//如果成功标记搜索到解过
stp--;//然后还原现场,在本层继续往下搜索
//排除重复解,如果相同的ai本次已经搜索过了
//如果无解,之后重复的ai不用搜索是显而易见的
//但是如果本次搜索有解,那也不必再搜后面的重复值了
//因为本次搜索的结果已经包含了后面的重复值了,因此不必再搜索了
//因此需要剪枝减掉!!
while ( i + 1 < n && a[i] == a[i + 1] ) i++;
}
return res;
}
int
main() {
int t;//和
int i;//计数变量
while ( scanf("%d%d", &t, &n), n ) {
stp = 0;
res = false;
for ( i = 0; i < n; i++ ) scanf("%d", a + i);
printf("Sums of %d:\n", t);
if ( 1 == n && *a != t || !dfs( t, 0 ) ) puts("NONE");//考虑一下特殊情况,可以略为加速
}
return 0;
}
无注释代码:
#include <iostream>
#include <cstdio>
#define MAXN 12
int n;
int stp;
bool res;
int a[MAXN];
int path[MAXN];
bool
dfs( int lft, int i ) {
int j;
if ( !lft ) {
printf("%d", *path);
for ( j = 1; j < stp; j++ ) printf("+%d", path[j]);
putchar('\n');
return true;
}
for ( ; i < n; i++ )
if ( a[i] <= lft ) {
path[stp++] = a[i];
if ( dfs( lft - a[i], i + 1 ) ) res = true;
stp--;
while ( i + 1 < n && a[i] == a[i + 1] ) i++;
}
return res;
}
int
main() {
int t;
int i;
while ( scanf("%d%d", &t, &n), n ) {
stp = 0;
res = false;
for ( i = 0; i < n; i++ ) scanf("%d", a + i);
printf("Sums of %d:\n", t);
if ( 1 == n && *a != t || !dfs( t, 0 ) ) puts("NONE");
}
return 0;
}