Sum It up
Time Limit: 1000MS |
|
Memory Limit: 10000K |
Total Submissions: 6682 |
|
Accepted: 3475 |
Description
Given a specified total T and a list of n integers, find all distinct sums using numbers from the list that add-to T. F or example, if T = 4, n = 6, and the list is [4, 3, 2, 2, 1, 1], then there be four different sums that equal 4:4, 3+1, 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 would contain one or more test cases, one per line. Each test case is contains T, the total, followed by N, the number of integers in the list, and followed by n integers x 1. . . , x N. If n = 0 It signals the end of the input; Otherwise, t be is a positive integer less than, n would be a integer between 1 and (inclusive), and X 1,. . . , x n would be is positive integers less than 100. All numbers is separated by exactly one space. The numbers in each list appear in nonincreasing order, and there could be repetitions.
Output
For each test case, first output a line containing ' Sums of ', the total, and a colon. Then output the sum, one per line; If there is no sums, output the line ' NONE '. The numbers within each sum must appear in nonincreasing order. A number is repeated in the sum as many times as it is repeated in the original list. The sums themselves must is sorted in decreasing order based on the numbers appearing in the sum. In other words, the sums must is sorted by their first number; Sums with the same first number must is sorted by their second number; Sums with the same first and numbers must is sorted by their third number; And so on. Within each test case, all sums must is distinct; The same sum cannot appear twice.
Sample Input
4 6 4 3 2 2 1 15 3 2 1 1400 12 50 50 50 50 50 50 25 25 25 25 25 250 0
Sample Output
Sums of 4:43+12+22+1+1sums of 5:nonesums of 400:50+50+50+50+50+50+25+25+25+2550+50+50+50+50+25+25+25+25+25+25
#include <stdio.h> #include <string.h> #define MAX 1100int n,m,k,ok;int a[max],b[max];void dfs (int pos,int Tot,int k) {int i,j;if (tot==n) {ok=1;for (j=0;j<k;j++) {if (!j) printf ("%d", b[j]), Else printf ("+%d", B[j]);} printf ("\ n"); return;} for (i=pos;i<m;i++) {B[k]=a[i];d FS (i+1,tot+a[i],k+1), while (a[i]==a[i+1])//go to Heavy ++i;}} int main () {int i,j;while (scanf ("%d%d", &n,&m), n|m) {for (i=0;i<m;i++) scanf ("%d", &a[i]); k=0;ok=0 ;p rintf ("Sums of%d:\n", N);d FS (0,0,0), if (!ok) printf ("none\n");} return 0;}
POJ 1564 Sum It up "dfs+ de-weight"