#include<bits/stdc++.h>
#include<algorithm>
using namespace std;
string num, foundAns[10001];
int k, x, y, ans;
vector<int> change[10],emptyVector;
inline bool foundString(string str){
for (int it = 0; it < ans;it++){
if(foundAns[it]==str){
return true;
}
}
return false;
}
inline bool CanBeReplaced(char c){
return change[ c - '0'] != emptyVector;
}
inline void putFoundString(string str){
foundAns[ans++] = str;
}
inline void bfs(){
queue<string> que;
que.push(num);
while(!(que.empty())){
string last = que.front();
que.pop();
for (long long unsigned int i = 0; i < last.size(); i++){
if(CanBeReplaced(last[i])){
string NewAns = last;
for (long long unsigned int j = 0;j<change[last[i]-'0'].size();j++){
NewAns[i] = change[last[i]-'0'][j] + '0';
if(!foundString(NewAns)){
que.push(NewAns);
putFoundString(NewAns);
}
}
}
}
}
}
int main(int argc, char const *argv[]){
cin >> num >> k;
foundAns[ans++] = num;
for (int i = 1; i <= k;i++){
cin >> x >> y;
change[x].push_back(y);
}
bfs();
cout << ans;
return 0;
}