題目大意:
現有多個測例,每個測例中給定一個和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;
}