#include"cstdio"
#include"string"
#include"iostream"
#include"vector"
using namespace std;
int num[50],ans[50],s;
long long sum = 1;
int len = 0;
vector<int>map[10];
char x;
bool book[10] = { false };
void DFS(int cur) {
int key = cur;
for (int i = 0; i < map[key].size(); i++) {
if (!book[map[key][i]]) {
book[map[key][i]] = true;
s++;
DFS(map[key][i]);
book[map[key][i]] = false;
}
}
}
int main() {
int k;
while (scanf("%c", &x) && x != ' ') {
num[len++] = x - '0';
}
cin >> k;
int key, value;
for (int i = 0; i < k; i++) {
scanf("%d%d", &key, &value);
map[key].push_back(value);
}
for (int i = 0; i < len; i++) {
s = 1;
book[num[i]] = true;
DFS(num[i]);
book[num[i]] = false;
ans[i] = s;
}
//高精度
vector<int>res;
res.push_back(ans[0]);
int p = 0;
for (int i = 1; i < len; i++) {
for (int j = 0; j < res.size(); j++) {
int t = ans[i] * res[j]+p;
res[j]= t % 10;
p = t / 10;
}
while(p) {
res.push_back(p%10);
p /= 10;
}
}
for (int i = res.size() - 1; i >= 0; i--) {
printf("%d", res[i]);
}
return 0;
}