#include <bits/stdc++.h>
#define maxx 1000005
#define Maxx 82
using namespace std;
int k;
int vst[maxx] , len;
char q[maxx][Maxx];
char st[Maxx] , s[Maxx];
struct NICE{int x , y;} a[Maxx];
//保存规则的数组
int init(char s[] , int len)
{ int ans = 0;
for (int i=0; i<len; i++)
{ ans *= 10;
ans += s[i] - '0';
}
return ans;
}
int main()
{ cin >> s;cin >> k;
len = strlen(s);
for (int i=1; i<=k; i++)cin >> a[i].x >> a[i].y ;
int head = 1 , tail = 1;//指针
int cnt = 1 , nt = init(s , len);
strcpy(q[tail] , s);
++tail;
vst[nt] = 1;
while (head < tail)
{ for (int i=1; i<=k; i++)
{ strcpy(st , q[head]);
for (int j=0; j<len; j++)
{ if (st[j] == a[i].x + '0')
{ st[j] = a[i].y + '0';
int Math = init(st , len);//转成数字
if (!vst[Math])
{ strcpy(q[tail] , st);//新的数字字符串加到队列中
++tail , ++cnt;
vst[Math] = 1;//标记
}strcpy(st , q[head]);//重新初始化st
}
}
}++head;
}cout << cnt;
}