//* Problem  : G - Matrix Chain Multiplication
//* Contest  : UzhNU Local
//* Origin   : Ulm-1996
//* Type     : Solution
//* Date     : 2008.02.04
//* Author   : alt
//* Language : C++
//* Compiler : Microsoft Visual C++ 6.0
//* Algoritm : Straightforward

#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>

int n, res, pos;

int x[256], y[256];

char s[100];

int parse_expr(int &xx, int &xy)
{
	if (s[pos] == '(')
	{
		pos++;
		int res, x1, y1, x2, y2, r1, r2;
		r1 = parse_expr(x1, y1);
		if (r1 < 0) return -1;
		r2 = parse_expr(x2, y2);
		if (r2 < 0) return -1;
		if (y1 != x2) return -1;
		xx = x1; xy = y2; res = x1 * y1 * y2 + r1 + r2;
		pos++;
		return res;
	}
	xx = x[s[pos]];	xy = y[s[pos]]; pos++; return 0;
}

int main()
{
	gets(s); sscanf(s, "%d", &n);
	char c; int xt, yt;
	for (int i = 0; i < n; i++)
	{
		gets(s); sscanf(s, "%c %d %d", &c, &xt, &yt);
		x[c] = xt; y[c] = yt;
	}
	while (!feof(stdin))
	{
		s[0] = 0; gets(s); if (!s[0]) continue;
		pos = 0;
		res = parse_expr(xt, yt);
		if (res == -1) printf("error\n");
			else printf("%d\n", res);
	}
	return 0;
}