#include<bits/stdc++.h>
#define ll long long
#define all(x) x.begin(), x.end()
using namespace std;
map<string, int> mp1, mp2;
bool motcaigiday(string s) {
for (int i = 1; i < s.size(); ++i) {
if (s[i] != s[i - 1]) return false;
}
return true;
}
int main() {
string daquy1, daquy2;
int n;
cin >> n;
getline(cin, daquy1);
for (int i = 0; i < daquy1.size(); ++i) {
int k = 0;
string xs = "";
while (daquy1[i] >= '0' && daquy1[i] <= '9') {
++i;
}
while (daquy1[i] >= 'A' && daquy1[i] <= 'Z') {
xs += daquy1[i];
++i;
}
while (daquy1[i] >= '0' && daquy1[i] <= '9') {
k = k * 10 + (daquy1[i] - 48);
++i;
}
if (motcaigiday(xs)) {
string a;
a += xs[0];
mp2[a] = k * (xs.size());
}
else {
sort(all(xs));
mp1[xs] = k;
}
}
getline(cin, daquy2);
for (int i = 0; i < daquy2.size(); ++i) {
int k = 0;
string xs = "";
while (daquy2[i] >= '0' && daquy2[i] <= '9') {
++i;
}
while (daquy2[i] >= 'A' && daquy2[i] <= 'Z') {
xs += daquy2[i];
++i;
}
while (daquy2[i] >= '0' && daquy2[i] <= '9') {
k = k * 10 + (daquy2[i] - 48);
++i;
}
if (motcaigiday(xs)) {
string a;
a += xs[0];
mp2[a] = k * (xs.size());
}
else {
sort(all(xs));
mp2[xs] = k;
}
}
}
I2luY2x1ZGU8Yml0cy9zdGRjKysuaD4KI2RlZmluZSBsbCBsb25nIGxvbmcKI2RlZmluZSBhbGwoeCkgeC5iZWdpbigpLCB4LmVuZCgpCnVzaW5nIG5hbWVzcGFjZSBzdGQ7Cm1hcDxzdHJpbmcsIGludD4gbXAxLCBtcDI7CmJvb2wgbW90Y2FpZ2lkYXkoc3RyaW5nIHMpIHsKCWZvciAoaW50IGkgPSAxOyBpIDwgcy5zaXplKCk7ICsraSkgewoJCWlmIChzW2ldICE9IHNbaSAtIDFdKSByZXR1cm4gZmFsc2U7Cgl9CglyZXR1cm4gdHJ1ZTsKfQppbnQgbWFpbigpIHsKCXN0cmluZ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