#include "_.h"

typedef struct node {
    long result;
    struct node *next_mul;
    struct node *next_add;
} node_t;

int cal(char **nbrs, node_t *cur, long i, long result) {
    if (nbrs[i] == NULL)
        return cur->result == result;

    long nbr1 = atol(nbrs[i]);

    cur->next_mul = calloc(1, sizeof(node_t));
    cur->next_add = calloc(1, sizeof(node_t));
    cur->next_mul->result = cur->result * nbr1;
    cur->next_add->result = cur->result + nbr1;

    return cal(nbrs, cur->next_mul, i + 1, result) ||
           cal(nbrs, cur->next_add, i + 1, result); 
}

int main(int argc, char **argv) {
	
	if (argc != 2)
		return 1;

	char *input = argv[1];
	char **inputs = str_split(strdup(input), '\n');


    long add = 0;
	for (long i = 0; inputs[i] != NULL; i++) {
        char **split_space = str_split(strdup(inputs[i]), ' ');
        long result = atol(split_space[0]);
        node_t *head = calloc(1, sizeof(node_t));
        head->result = atol(split_space[1]);
        int find = cal(split_space, head, 2, result);

        //printf("result: %ld\n", result);
        //printf("find: %ld\n", find);
        if (find)
            add += result;
	}

    printf("add: %ld\n", add);

	return 0;
}
