//* Problem  : 2318 - Chemical reactions
//* Contest  : acm.tju.edu.cn
//* Type     : Solution
//* Date     : 2007.09.22
//* Author   : alt
//* Language : C++
//* Compiler : Microsoft Visual C++ 6.0


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

struct chem{
	char id[2];
	int count;
};

struct formula{
	char s[110];
	int chem_count;
	chem a[100];
} f_main, f_curr;

int n, pos;
char s[200];

void solve();
void result();

formula parse_sequence(int coef);

int parse_number()
{
	int res = 0;
	while (s[pos] >= '0' && s[pos] <= '9')
		res = res * 10 + s[pos++] - '0';
	if (!res) return 1;
		else return res;
}

void normalize_formula(formula *res)
{
	int i, j, n = res->chem_count;
	for (j = 0; j < n - 1; j++)
		for (i = 0; i < n - 1; i++)
			if (res->a[i].id[0] < res->a[i+1].id[0] ||
				(res->a[i].id[0] == res->a[i+1].id[0] && res->a[i].id[1] < res->a[i+1].id[1]))
			{
				chem t = res->a[i]; res->a[i] = res->a[i+1]; res->a[i+1] = t;
			}
}

int equal_formulas()
{
	if (f_main.chem_count != f_curr.chem_count) return 0;
	for (int i = 0; i < f_main.chem_count; i++)
	{
		if (f_main.a[i].count != f_curr.a[i].count) return 0;
		if (f_main.a[i].id[0] != f_curr.a[i].id[0]) return 0;
		if (f_main.a[i].id[1] != f_curr.a[i].id[1]) return 0;
	}
	return 1;
}

void add_chem(formula *res, chem t)
{
	for (int i = 0; i < res->chem_count; i++)
		if (res->a[i].id[0] == t.id[0] && res->a[i].id[1] == t.id[1])
		{
			res->a[i].count += t.count;
			return;
		}
	int k = res->chem_count++;
	res->a[k] = t;
}

void add_formulas(formula *res, formula t)
{
	for (int i = 0; i < t.chem_count; i++)
		add_chem(res, t.a[i]);
}

formula parse_element(int coef)
{
	formula res;
	if (s[pos] == '(')
	{
		pos++;
		res = parse_sequence(coef);
		pos++;
		return res;
	}
	else
	{
		memset(&res, 0, sizeof(res));
		res.chem_count = 1;
		res.a[0].id[0] = s[pos++];
		if (s[pos] >= 'a' && s[pos] <= 'z') res.a[0].id[1] = s[pos++];
		res.a[0].count = coef;
		return res;
	}
}

formula parse_sequence(int coef)
{
	formula res = parse_element(coef), t;
	int c = parse_number(), i;
	for (i = 0; i < res.chem_count; i++)
		res.a[i].count *= c;
	while (s[pos] == '(' || (s[pos] >='A' && s[pos] <= 'Z'))
	{
		t = parse_element(coef);
		c = parse_number();
		for (i = 0; i < t.chem_count; i++)
			t.a[i].count *= c;
		add_formulas(&res, t);
	}
	return res;
}

formula parse_formula(int coef)
{
	formula res, t; 
	int c = parse_number();
	res = parse_sequence(coef * c);
	while (s[pos] == '+')
	{
		pos++;
		c = parse_number();
		t = parse_sequence(coef * c);
		add_formulas(&res, t);
	}
	return res;
}

formula parse()
{
	pos = 0;
	return parse_formula(1);
}

int main()
{
	scanf("%s", s); f_main = parse(); strcpy(f_main.s, s); normalize_formula(&f_main);
	scanf("%s", s); sscanf(s, "%d", &n);
	while (n--)
	{
		scanf("%s", s); f_curr = parse(); normalize_formula(&f_curr);
		printf("%s%c=%s\n", f_main.s, (equal_formulas()?'=':'!'), s);
	}
	return 0;
}


