Sum It Up

来源:百度知道 编辑:UC知道 时间:2024/06/07 09:00:15
Given a specified total t and a list of n integers, find all distinct sums using numbers from the list that add up to t. For example, if t = 4, n = 6, and the list is [4, 3, 2, 2, 1, 1], then there are four different sums that equal 4: 4, 3+1, 2+2, and 2+1+1. (A number can be used within a sum as many times as it appears in the list, and a single number counts as a sum.) Your job is to solve this problem in general.

Input

The input file will contain one or more test cases, one per line. Each test case contains t, the total, followed by n, the number of integers in the list, followed by n integers x 1 , . . . , x n . If n = 0 it signals the end of the input; otherwise, t will be a positive integer less than 1000, n will be an integer between 1 and 12 (inclusive), and x 1 , . . . , x n will be positive integers less than 100. All numbers will be separated by exactly one space. The numbers in each list appear in nonincreasing order, and there may be repetitions.

#include<stdio.h>
#include<string.h>

int num[13];
int x[13];
int sum,n;
int cw;
int result[1000][13];
int count;

void backtrack(int t)
{
if(t>n)
{
if(cw==sum)
{
int i;
for(i=1;i<t;i++)
{
result[count][i]=x[i];
}
count++;
}
}
else
{
if(cw+num[t]<=sum)
{
cw+=num[t];
x[t]=1;
backtrack(t+1);
cw-=num[t];
}
x[t]=0;
backtrack(t+1);
}
}

int main(void)
{
while(scanf("%d%d",&sum,&n)==2&&(sum||n))
{
int i;
cw=0;
count=0;
for(i=1;i<=n;i++)
scanf("