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

int used = 0;
char str[32];
void eval()
{
	char	*p, *q;
	int	a,b,c;
	a = strtol(str, 0, 10);
	q = strchr(str, '=');	c = strtol(q + 1, 0, 10);
	p = strchr(str, '+');
	if(p) {
		b = strtol(p + 1, 0, 10);
		if(p[1] == '0' || q[1] == '0') return;
		if((a + b) == c){
			printf("  %s\n", str);
		}
	}

	p = strchr(str, '-');
	if(p) {
		b = strtol(p + 1, 0, 10);
		if(p[1] == '0' || q[1] == '0') return;
		if((a - b) == c){
			printf("  %s\n", str);
		}
	}
}

void recur(int offs)
{
	int	c,n,i,old_used=used;
	char old_str[32];
	if((c = str[offs]) == 0) {
		eval();
		return;
	}
	if(! isalpha(c)) {
		recur(offs + 1);
		return;
	}

	strcpy(old_str, str);
	for(n=((offs == 0)?1:0); n<10; n++) {
		if(!(used & (1 << n))) {
			used |= (1 << n);
			for(i=0; str[i]; i++) {
				if(str[i] == c) str[i] = '0' + n;
			}
			recur(offs + 1);
			used = old_used;
			strcpy(str, old_str);
		}
	}
}

main()
{
	strcpy(str, "SEND+MORE=MONEY");
	printf("\n%s\n", str);
	recur(0);

	strcpy(str, "WWWDOT-GOOGLE=DOTCOM");
	printf("\n%s\n", str);
	recur(0);
	return 0;
}

