Photolog

Through the Looking-Glass
2010-10-12: Through the Looking-Glass
My radio speaks is binary!
2010-10-10: My radio speaks is binary!
Gigaminx: (present for my birthday)
2010-09-16: Gigaminx: (present for my birthday)
Trini on bike
2010-09-05: Trini on bike
Valporquero
2010-08-28: Valporquero
My new bike!
2010-08-22: My new bike!
Mario and Ana's wedding
2010-08-13: Mario and Ana's wedding
Canyoning in Guara
2010-08-07: Canyoning in Guara
Trini and Mari in Marbella
2010-08-05: Trini and Mari in Marbella
Trini and Chelo in Tabarca
2010-08-03: Trini and Chelo in Tabarca
Valid XHTML 1.1
Log in
Back to list of problems

Sum It Up

574.c

/* Sum It Up */
#include <stdio.h>
#include <stdlib.h>

int t,n;
int nums[12];
int used[12];

int
calc(int total, int first) {
	int i,j;
	int done;

	done=0;
	for(i=first; i<n; i++) {
		if (used[i]) {
			continue;
		}
		if (total == nums[i]) {
			for(j=0; j<i; j++) {
				if (used[j]) {
					printf("%d+", nums[j]);
				}
			}
			printf("%d\n", nums[i]);
			while(i<n && nums[i+1]==nums[i]) {
				i++;
			}
			done=1;
		} else if (total > nums[i]) {
			used[i]=1;
			done += calc(total-nums[i], i+1);
			used[i]=0;
			while(i<n && nums[i+1]==nums[i]) {
				i++;
			}
		}
	}
	return done;
}

int
main(void) {
	int i;

	while(1) {
		scanf("%d %d", &t, &n);
		for(i=0; i<n; i++) {
			scanf("%d", &nums[i]);
			used[i]=0;
		}
		if (n==0) {
			break;
		}
		printf("Sums of %d:\n", t);
		if (!calc(t, 0)) {
			printf("NONE\n");
		}
	}
	exit(0);
}