//Code by Patcas Csaba #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; #define LL long long #define PII pair #define VB vector #define VI vector #define VD vector #define VS vector #define VPII vector > #define VVI vector < VI > #define VVB vector < VB > #define FORN(i, n) for(int i = 0; i < (n); ++i) #define FOR(i, a, b) for(int i = (a); i <= (b); ++i) #define FORD(i, a, b) for(int i = (a); i >= (b); --i) #define REPEAT do{ #define UNTIL(x) }while(!(x)); #define SZ size() #define BG begin() #define EN end() #define CL clear() #define X first #define Y second #define RS resize #define PB push_back #define MP make_pair #define ALL(x) x.begin(), x.end() #define IN_FILE "a.in" #define OUT_FILE "a.out" #define BASE 666013 string s, halfString; int n; VS a; map >, LL> memo; map sols; LL f(int index, char lastChar, string used, string built) { if (memo.count(MP(index, MP(lastChar, used))) != 0) return (memo.find(MP(index, MP(lastChar, used))))->Y; if (index == 0) { built+=lastChar; ++sols[built]; return 1; } LL ans = 0; string oldUsed = used; FORN(i, used.SZ) { if (i > 0 && used[i] == used[i - 1]) continue; char prevChar = used[i]; bool ok = true; FOR(j, 1, n) if (a[j][0] == lastChar && a[j][2] == prevChar || a[j][2] == lastChar && a[j][0] == prevChar) { ok = false; break; } if (ok) { ans = (ans + f(index - 1, prevChar, used.erase(used.find(prevChar), 1), built+lastChar)) % BASE; used = oldUsed; } } memo.insert(MP(MP(index, MP(lastChar, used)), ans)); return ans; } int main() { //Read data //freopen(IN_FILE, "r", stdin); //freopen(OUT_FILE, "w", stdout); getline(cin, s); cin >> n; a.RS(n + 1); FOR(i, 0, n) getline(cin, a[i]); map count; FORN(i, s.SZ) ++count[s[i]]; int countOdd = 0; char oddChar; for(map::iterator it = count.BG; it != count.EN; ++it) { if (it->Y & 1) { ++countOdd; oddChar = it->X; } FORN(i, (it->Y + 1) / 2) halfString += it->X; } if (countOdd > 1) { cout << 0 << endl; return 0; } string oldHalfString = halfString; LL sum = 0; if ((s.SZ & 1) == 0) { for(map::iterator it = count.BG; it != count.EN; ++it) { bool ok = true; FOR(j, 1, n) if (a[j][0] == it->X && a[j][2] == it->X) { ok = false; break; } if (ok) sum = (sum + f((s.SZ - 1) / 2, it->X, halfString.erase(halfString.find(it->X), 1), "")) % BASE; halfString = oldHalfString; } } else if (s.SZ == 1) sum = 1; else { if (s.SZ == 3) { bool ok = true; FOR(j, 1, n) if (a[j][0] == halfString[0] && a[j][2] == halfString[1] || a[j][0] == halfString[1] && a[j][2] == halfString[0]) { ok = false; break; } if (ok) sum = 1; else sum = 0; } else sum = (sum + f((s.SZ - 1) / 2, oddChar, halfString.erase(halfString.find(oddChar), 1), "")) % BASE; } cout << sum << endl; return 0; }