#include "_.h"

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

void cal(char **nbrs, node_t *cur, long long i) {
    if (nbrs[i] == NULL)
        return;

    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]);

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

long long dis(node_t *cur, char *number_to_find) {
    if (cur->next_add == NULL) {
        //printf("cal: %s\n", cur->result);
        if (strcmp(cur->result, number_to_find) == 0) {
            return 1;
        }
        return 0;
    }

    long long find = dis(cur->next_mul, number_to_find);
    long long find2 = dis(cur->next_add, number_to_find);
    long long find3 = dis(cur->next_con, number_to_find);
    return find || find2 || find3;
}

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];
        cal(split_space, head, 2);

        //printf("result: %lld\n", result);
        long long find = dis(head, split_space[0]);
        //printf("find: %lld\n", find);
        if (find)
            add += result;
	}

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

	return 0;
}
