
#include "_.h"

typedef struct node {
    char *result;
    struct node *next_mul;
    struct node *next_add;
    struct node *next_con;
} node_t;

int cal(char **nbrs, node_t *cur, long long i, char* target) {
    if (nbrs[i] == NULL) {
        //printf("cal: %s\n", cur->result);
        return strcmp(cur->result, target) == 0;
    }

    long long nbr1 = atoll(nbrs[i]);
    long long result = atoll(cur->result);

    cur->next_mul = calloc(1, sizeof(node_t));
    cur->next_mul->result = calloc(100, 1);
    cur->next_add = calloc(1, sizeof(node_t));
    cur->next_add->result = calloc(100, 1);
    cur->next_con = calloc(1, sizeof(node_t));
    cur->next_con->result = calloc(100, 1);
    sprintf(cur->next_mul->result, "%lld", result * nbr1);
    sprintf(cur->next_add->result, "%lld", result + nbr1);
    cur->next_con->result = strcat(cur->result, nbrs[i]);

    if (cal(nbrs, cur->next_mul, i + 1, target))
        return 1;
    if (cal(nbrs, cur->next_add, i + 1, target))
        return 1;
    if (cal(nbrs, cur->next_con, i + 1, target))
        return 1;
    return 0;
}

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

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


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

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

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

	return 0;
}
