#include <iostream>
#include <fstream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <math.h>
#include <cmath>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <iomanip>
#include <limits.h>
#define _ ios_base::sync_with_stdio(0);cin.tie(0);
#define rep(i, n) for(LL i = 0; i < n; i++)
#define START clock_t _clock = clock();
#define END cout << "time:" << (double)(clock() - _clock) / (CLOCKS_PER_SEC) << endl;
#define MOD 1000000007
typedef long long LL;
LL max(LL x,LL y){return x>y?x:y;}
LL min(LL x,LL y){return x<y?x:y;}
using namespace std;
// Goooooooooooooooooooooooooooooooooooooooooogle chrome

const LL N = 1e5 + 9;

// Let it go! Let it go! Can't hold it back anymore! Let it go! Let it go! Turn away and slam the door!

LL dp[10], tp[10];
string a[N], s;
char in[N];

int main()
{_
    int i, j, k, l, q;
    LL ans, p;
    for(i = 0; i < 10; i++){
        dp[i] = i;
        tp[i] = 10;
    }
    cin >> s >> q;
    for(i = 0; i < q; i++){
        cin >> a[i];
    }
    for(i = q - 1; i >= 0; i--){
        k = a[i][0] - '0';
        ans = 0;
        p = 1;
        for(j = a[i].length() - 1; j >= 3; j--){
            l = a[i][j] - '0';
            (ans += dp[l] * p) %= MOD;
            (p *= tp[l]) %= MOD;
        }
        dp[k] = ans;
        tp[k] = p;
    }
    ans = 0;
    p = 1;
    for(i = s.length() - 1; i >= 0; i--){
        j = s[i] - '0';
        (ans += (dp[j] * p)) %= MOD;
        (p *= tp[j]) %= MOD;
    }
    cout<< ans <<endl;
    return 0;
}


#include <iostream>
#include <fstream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <math.h>
#include <cmath>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <iomanip>
#include <limits.h>
#define _ ios_base::sync_with_stdio(0);cin.tie(0);
#define rep(i, n) for(LL i = 0; i < n; i++)
#define START clock_t _clock = clock();
#define END cout << "time:" << (double)(clock() - _clock) / (CLOCKS_PER_SEC) << endl;
#define MOD 1000000007
typedef long long LL;
LL max(LL x,LL y){return x>y?x:y;}
LL min(LL x,LL y){return x<y?x:y;}
using namespace std;
// Goooooooooooooooooooooooooooooooooooooooooogle chrome

const LL N = 1e5 + 9;

// Let it go! Let it go! Can't hold it back anymore! Let it go! Let it go! Turn away and slam the door!

LL dp[10], tp[10];
string a[N], s;
char in[N];

int main()
{_
    int i, j, k, l, q;
    LL ans, p;
    for(i = 0; i < 10; i++){
        dp[i] = i;
        tp[i] = 10;
    }
    cin >> s >> q;
    for(i = 0; i < q; i++){
        scanf("%s", in);
        a[i] = in;
    }
    for(i = q - 1; i >= 0; i--){
        k = a[i][0] - '0';
        ans = 0;
        p = 1;
        for(j = a[i].length() - 1; j >= 3; j--){
            l = a[i][j] - '0';
            (ans += dp[l] * p) %= MOD;
            (p *= tp[l]) %= MOD;
        }
        dp[k] = ans;
        tp[k] = p;
    }
    ans = 0;
    p = 1;
    for(i = s.length() - 1; i >= 0; i--){
        j = s[i] - '0';
        (ans += (dp[j] * p)) %= MOD;
        (p *= tp[j]) %= MOD;
    }
    cout<< ans <<endl;
    return 0;
}


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define long long long
#define NN 101010
#define mod ((long)1e9 + 7)
int n;
char s[NN], t[NN], c[NN], * b[NN];
long p[10], len[10];

long mpow(long base, long m) {
    long ans = 1;
    for (; m > 0; m >>= 1) {
        if (m & 1) ans = (ans * base) % mod;
        base = (base * base) % mod;
    }
    return ans;
}

void process(char* s, long* val, long* l) {
    *val = *l = 0;
    int i = 0; while (s[i]) ++i;
    while (i --) {
        *val = (*val + (p[s[i] - '0'] * mpow(10, *l)) % mod) % mod;
        *l = (*l + len[s[i] - '0']) % (mod - 1);
    }
}

int main() {
    #ifndef ONLINE_JUDGE
    freopen("transform.inp", "r", stdin);
    freopen("transform.out", "w", stdout);
    #endif

    int i;
    memset(t, 0, sizeof(t));
    char *pt = t;
    scanf("%s", s);
    scanf("%d", &n);
    b[0] = s;
    c[0] = 0;
    for (i = 1; i <= n; ++i) {
        scanf("%s", pt);
        c[i] = pt[0] - '0';
        b[i] = pt + 3;
        while (*pt) ++pt;
        ++pt;
    }

    for (i = 0; i < 10; ++i) {
        p[i] = i;
        len[i] = 1;
    }

    for (i = n; i >= 0; --i) {
        long f, g;
        process(b[i], &f, &g);
        p[(int)c[i]] = f; len[(int)c[i]] = g;
    }

    printf("%d", (int)p[0]);

    return 0;
}


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define long long long
#define NN 501010
#define mod ((long)1e9 + 7)
int n;
char s[NN], t[NN], c[NN], * b[NN];
long p[10], len[10];

long mpow(long base, long m) {
    long ans = 1;
    for (; m > 0; m >>= 1) {
        if (m & 1) ans = (ans * base) % mod;
        base = (base * base) % mod;
    }
    return ans;
}

void process(char* s, long* val, long* l) {
    *val = *l = 0;
    int i = 0; while (s[i]) ++i;
    while (i --) {
        *val = (*val + (p[s[i] - '0'] * mpow(10, *l)) % mod) % mod;
        *l = (*l + len[s[i] - '0']) % (mod - 1);
    }
}

int main() {
    #ifndef ONLINE_JUDGE
    freopen("transform.inp", "r", stdin);
    freopen("transform.out", "w", stdout);
    #endif

    int i;
    memset(t, 0, sizeof(t));
    char *pt = t;
    scanf("%s", s);
    scanf("%d", &n);
    b[0] = s;
    c[0] = 0;
    for (i = 1; i <= n; ++i) {
        scanf("%s", pt);
        c[i] = pt[0] - '0';
        b[i] = pt + 3;
        while (*pt) ++pt;
        ++pt;
    }

    for (i = 0; i < 10; ++i) {
        p[i] = i;
        len[i] = 1;
    }

    for (i = n; i >= 0; --i) {
        long f, g;
        process(b[i], &f, &g);
        p[(int)c[i]] = f; len[(int)c[i]] = g;
    }

    printf("%d", (int)p[0]);

    return 0;
}


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define long long long
#define NN 101010
#define mod ((long)1e9 + 7)
int n;
char s[NN], t[NN], c[NN], * b[NN];
char p[10][NN], temp[NN];

int main() {
    #ifndef ONLINE_JUDGE
    freopen("transform.inp", "r", stdin);
    freopen("transform.out", "w", stdout);
    #endif

    int i, f, g;
    memset(t, 0, sizeof(t));
    char *pt = t;
    scanf("%s", s);
    scanf("%d", &n);
    b[0] = s;
    for (i = 1; i <= n; ++i) {
        scanf("%s", pt);
        c[i] = pt[0] - '0';
        b[i] = pt + 3;
        while (*pt) ++pt; ++pt;
    }

    for (i = 0; i < 10; ++i) {
        p[i][1] = 0;
        p[i][0] = i + '0';
    }

    for (i = n; i >= 0; --i) {
        memset(temp, 0, sizeof(temp)); pt = temp;
        for (f = 0; b[i][f]; ++f) {
            for (g = 0; p[b[i][f] - '0'][g]; ++g, ++pt) {
                *pt = p[b[i][f] - '0'][g];
            }
        }
        if (i > 0) memcpy(p[(int)c[i]], temp, sizeof(temp));
    }

    long ans = 0;
//    fprintf(stderr, "%s\n", temp);
    for (i = 0; temp[i]; ++i);
    long p10 = 1;
    f = 0;
    while (i--) {
        ans = (ans + p10 * (temp[i] - '0') % mod) % mod;
        p10 = (p10 * (long)10) % mod;
        ++f;
//        fprintf(stderr, "%d %ld\n", f, p10);
    }

    printf("%d", (int)ans);

    return 0;
}


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define NN 101010
#define mod ((long)1e9 + 7)
int n;
char s[NN], t[NN], c[NN], * b[NN];
char p[10][NN], temp[NN];

int main() {
    freopen("transform.inp", "r", stdin);
    freopen("transform.out", "w", stdout);

    int i, f, g;
    memset(t, 0, sizeof(t));
    char *pt = t;
    scanf("%s", s);
    scanf("%d", &n);
    b[0] = s;
    for (i = 1; i <= n; ++i) {
        scanf("%s", pt);
        c[i] = pt[0] - '0';
        b[i] = pt + 3;
        while (*pt) ++pt; ++pt;
    }

    for (i = 0; i < 10; ++i) {
        p[i][1] = 0;
        p[i][0] = i + '0';
    }

    for (i = n; i >= 0; --i) {
        memset(temp, 0, sizeof(temp)); pt = temp;
        for (f = 0; b[i][f]; ++f) {
            for (g = 0; p[b[i][f] - '0'][g]; ++g, ++pt) {
                *pt = p[b[i][f] - '0'][g];
            }
        }
        if (i > 0) memcpy(p[(int)c[i]], temp, sizeof(temp));
    }

    long ans = 0;
//    fprintf(stderr, "%s\n", temp);
    for (i = 0; temp[i]; ++i);
    long p10 = 1;
    f = 0;
    while (i--) {
        ans = (ans + p10 * (temp[i] - '0') % mod) % mod;
        p10 = (p10 * (long)10) % mod;
        ++f;
//        fprintf(stderr, "%d %ld\n", f, p10);
    }

    printf("%ld", ans);

    return 0;
}


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define NN 101010
#define mod ((long)1e9 + 7)
int n;
char s[NN], t[NN], c[NN], * b[NN];
char p[10][NN], temp[NN];

int main() {
    #ifndef ONLINE_JUDGE
    freopen("transform.inp", "r", stdin);
    freopen("transform.out", "w", stdout);
    #endif

    int i, f, g;
    memset(t, 0, sizeof(t));
    char *pt = t;
    scanf("%s", s);
    scanf("%d", &n);
    b[0] = s;
    for (i = 1; i <= n; ++i) {
        scanf("%s", pt);
        c[i] = pt[0] - '0';
        b[i] = pt + 3;
        while (*pt) ++pt; ++pt;
    }

    for (i = 0; i < 10; ++i) {
        p[i][1] = 0;
        p[i][0] = i + '0';
    }

    for (i = n; i >= 0; --i) {
        memset(temp, 0, sizeof(temp)); pt = temp;
        for (f = 0; b[i][f]; ++f) {
            for (g = 0; p[b[i][f] - '0'][g]; ++g, ++pt) {
                *pt = p[b[i][f] - '0'][g];
            }
        }
        if (i > 0) memcpy(p[(int)c[i]], temp, sizeof(temp));
    }

    long ans = 0;
//    fprintf(stderr, "%s\n", temp);
    for (i = 0; temp[i]; ++i);
    long p10 = 1;
    f = 0;
    while (i--) {
        ans = (ans + p10 * (temp[i] - '0') % mod) % mod;
        p10 = (p10 * (long)10) % mod;
        ++f;
//        fprintf(stderr, "%d %ld\n", f, p10);
    }

    printf("%ld", ans);

    return 0;
}


// Codeforces Round #265 (Div.1) C. Substitutes in Number (464/C)

import java.util.*;
import java.util.AbstractMap.SimpleEntry;

public class SubstitutesInNumber {
  public static void main(String[] args) {
    Solver solver = new Solver();
    solver.solve();
  }
}

class Solver {
  private final long MOD = 1000000007;

  private String s;
  private int n;
  private Rule[] rules;
  private DPEntry[][] dp;

  public void solve() {
    Scanner scan = new Scanner(System.in);

    this.s = scan.next();
    this.n = scan.nextInt();
    this.rules = new Rule[this.n + 1];
    this.dp = new DPEntry[this.n + 1][10];

    for (int i = 1; i <= n; ++i) {
      String[] rule = scan.next().split("->");

      int key = Integer.parseInt(rule[0]);
      String value = rule.length > 1 ? rule[1] : "";

      this.rules[i] = new Rule(key, value);
    }
    this.rules[0] = new Rule(0, this.s);

    System.out.println(Search(0, 0).value);
  }

  private DPEntry Search(int depth, int key) {
    if (depth > n) {
      return new DPEntry(1, key);
    }
    if (this.dp[depth][key] == null) {
      this.dp[depth][key] = new DPEntry();
    }
    if (this.dp[depth][key].value != -1) {
      return this.dp[depth][key];
    }
    if (this.rules[depth].key == key) {
      DPEntry entry = new DPEntry(0, 0);
      for (char c : this.rules[depth].value.toCharArray()) {
        DPEntry res = Search(depth + 1, (int)c - '0');
        entry.digits += res.digits;
        for (int i = 0; i < res.digits; ++i) {
          entry.value = (entry.value * 10) % MOD;
        }
        entry.value = (entry.value + res.value) % MOD;
      }
      this.dp[depth][key] = entry;
    } else {
      this.dp[depth][key] = Search(depth + 1, key);
    }
    return this.dp[depth][key];
  }

  class Rule {
    public int key;
    public String value;

    public Rule() {
      this.key = -1;
      this.value = "";
    }

    public Rule(int key, String value) {
      this.key = key;
      this.value = value;
    }
  }

  class DPEntry {
    public long digits;
    public long value;

    public DPEntry() {
      this.digits = -1;
      this.value = -1;
    }

    public DPEntry(long digits, long value) {
      this.digits = digits;
      this.value = value;
    }
  }
}


// Codeforces Round #265 (Div.1) C. Substitutes in Number (464/C)

import java.util.*;
import java.util.AbstractMap.SimpleEntry;

public class SubstitutesInNumber {
  public static void main(String[] args) {
    Solver solver = new Solver();
    solver.solve();
  }
}

class Solver {
  private final long MOD = 1000000007;

  private String s;
  private int n;
  private Rule[] rules;
  private DPEntry[][] dp;

  public void solve() {
    Scanner scan = new Scanner(System.in);

    this.s = scan.next();
    this.n = scan.nextInt();
    this.rules = new Rule[this.n + 1];
    this.dp = new DPEntry[this.n + 1][10];

    for (int i = 1; i <= n; ++i) {
      String[] rule = scan.next().split("->");

      int key = Integer.parseInt(rule[0]);
      String value = rule.length > 1 ? rule[1] : "";

      this.rules[i] = new Rule(key, value);
    }
    this.rules[0] = new Rule(0, this.s);

    System.out.println(Search(0, 0).value);
  }

  private DPEntry Search(int depth, int key) {
    if (depth > n) {
      return new DPEntry(10, key);
    }
    if (this.dp[depth][key] != null) {
      return this.dp[depth][key];
    }
    if (this.rules[depth].key == key) {
      DPEntry entry = new DPEntry(1, 0);
      for (char c : this.rules[depth].value.toCharArray()) {
        DPEntry res = Search(depth + 1, (int)c - '0');
        entry.digits = (entry.digits * res.digits) % MOD;
        entry.value = (entry.value * res.digits + res.value) % MOD;
      }
      this.dp[depth][key] = entry;
    } else {
      this.dp[depth][key] = Search(depth + 1, key);
    }
    return this.dp[depth][key];
  }

  class Rule {
    public int key;
    public String value;

    public Rule() {
      this.key = -1;
      this.value = "";
    }

    public Rule(int key, String value) {
      this.key = key;
      this.value = value;
    }
  }

  class DPEntry {
    public long digits;
    public long value;

    public DPEntry() {
      this.digits = -1;
      this.value = -1;
    }

    public DPEntry(long digits, long value) {
      this.digits = digits;
      this.value = value;
    }
  }
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author Bat-Orgil
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskC solver = new TaskC();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskC {
        static long mod = 1000000007;

        public void solve(int testNumber, InputReader in, PrintWriter out) {
            String s = in.next();
            int m = in.nextInt();
            int[] left = new int[m];
            String[] right = new String[m];

            for (int i = 0; i < m; i++) {
                String t = in.next();
                left[i] = t.charAt(0) - '0';
                right[i] = t.substring(3);
            }

            long[] val = new long[10];
            long[] shift = new long[10];
            for (int i = 0; i < 10; i++) {
                val[i] = i;
                shift[i] = 10;
            }

            for (int i = m - 1; i >= 0; i--) {
                long newVal = 0;
                long newShift = 1;

                for (int j = 0; j < right[i].length(); j++) {
                    int c = right[i].charAt(j) - '0';
                    newVal = (newVal * shift[c] + val[c]) % mod;
                    newShift = (newShift * shift[c]) % mod;
                }
                val[left[i]] = newVal;
                shift[left[i]] = newShift;
            }
            long v = 0;
            for (int i = 0; i < s.length(); i++) {
                v = (v * shift[s.charAt(i) - '0'] + val[s.charAt(i) - '0']) % mod;
            }
            out.println(v);

        }

    }

    static class InputReader {
        public BufferedReader reader;
        public StringTokenizer tokenizer;

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream), 32768);
            tokenizer = null;
        }

        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

    }
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.Writer;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 * @author ilyakor
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        OutputWriter out = new OutputWriter(outputStream);
        TaskC solver = new TaskC();
        solver.solve(1, in, out);
        out.close();
    }
}

class TaskC {
    static final long mod = 1000000007;

    public void solve(int testNumber, InputReader in, OutputWriter out) {
        long[] vals = new long[10];
        long[] shifts = new long[10];
        for (int i = 0; i < 10; ++i) {
            vals[i] = i;
            shifts[i] = 10;
        }
        String s = in.nextToken();
        int m = in.nextInt();
        int[] left = new int[m];
        String[] right = new String[m];
        for (int i = 0; i < m; ++i) {
            String cur = in.nextToken();
            left[i] = cur.charAt(0) - '0';
            right[i] = cur.substring(3);
        }
        for (int i = m - 1; i >= 0; --i) {
            long newVal = 0;
            long newShift = 1;
            for (int j = 0; j < right[i].length(); ++j) {
                int c = right[i].charAt(j) - '0';
                newVal = (newVal * shifts[c] + vals[c]) % mod;
                newShift = (newShift * shifts[c]) % mod;
            }
            vals[left[i]] = newVal;
            shifts[left[i]] = newShift;
        }
        long val = 0;
        for (int j = 0; j < s.length(); ++j) {
            int c = s.charAt(j) - '0';
            val = (val * shifts[c] + vals[c]) % mod;
        }
        out.printLine(val);
    }
}

class InputReader {
    private InputStream stream;
    private byte[] buffer = new byte[10000];
    private int cur;
    private int count;

    public InputReader(InputStream stream) {
        this.stream = stream;
    }

    public static boolean isSpace(int c) {
        return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
    }

    public int read() {
        if (count == -1) {
            throw new InputMismatchException();
        }
        try {
            if (cur >= count) {
                cur = 0;
                count = stream.read(buffer);
                if (count <= 0)
                    return -1;
            }
        } catch (IOException e) {
            throw new InputMismatchException();
        }
        return buffer[cur++];
    }

    public int readSkipSpace() {
        int c;
        do {
            c = read();
        } while (isSpace(c));
        return c;
    }

    public String nextToken() {
        int c = readSkipSpace();
        StringBuilder sb = new StringBuilder();
        while (!isSpace(c)) {
            sb.append((char) c);
            c = read();
        }
        return sb.toString();
    }

    public int nextInt() {
        int sgn = 1;
        int c = readSkipSpace();
        if (c == '-') {
            sgn = -1;
            c = read();
        }
        int res = 0;
        do {
            if (c < '0' || c > '9') {
                throw new InputMismatchException();
            }
            res = res * 10 + c - '0';
            c = read();
        } while (!isSpace(c));
        res *= sgn;
        return res;
    }

}

class OutputWriter {
    private final PrintWriter writer;

    public OutputWriter(OutputStream outputStream) {
        writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
    }

    public OutputWriter(Writer writer) {
        this.writer = new PrintWriter(writer);
    }

    public void print(Object... objects) {
        for (int i = 0; i < objects.length; i++) {
            if (i != 0) {
                writer.print(' ');
            }
            writer.print(objects[i]);
        }
    }

    public void printLine(Object... objects) {
        print(objects);
        writer.println();
    }

    public void close() {
        writer.close();
    }

}


import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import java.math.BigInteger;
import static java.math.BigInteger.*;
import static java.util.Arrays.*;
import javax.xml.ws.Holder;

//<editor-fold defaultstate="collapsed" desc="Main">
public class Task{
// https://netbeans.org/kb/73/java/editor-codereference_ru.html#display
    private void run() {
        try {
            Locale.setDefault(Locale.US);
        } catch (Exception e) {
        }
        boolean oj = true;
        try {
            oj = System.getProperty("MYLOCAL") == null;
        } catch (Exception e) {
        }

        if (oj) {
            sc = new FastScanner(new InputStreamReader(System.in));
            out = new PrintWriter(new OutputStreamWriter(System.out));
        } else {
            try {
                sc = new FastScanner(new FileReader("input.txt"));
                out = new PrintWriter(new FileWriter("output.txt"));
            } catch (IOException e) {
                MLE();
            }
        }
        Solver s = new Solver();
        s.sc = sc;
        s.out = out;
        s.solve();
        if (!oj) {
            err.println("Time: " + (System.currentTimeMillis() - timeBegin) / 1e3);
            err.printf("Mem: %d\n", (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) >> 20);
        }
        out.flush();
    }

    private void show(int[] arr) {
        for (int v : arr) {
            err.print(" " + v);
        }
        err.println();
    }

    public static void exit() {
        err.println("Time: " + (System.currentTimeMillis() - timeBegin) / 1e3);
        out.flush();
        out.close();
        System.exit(0);
    }

    public static void MLE() {
        int[][] arr = new int[1024 * 1024][];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = new int[1024 * 1024];
        }
    }

    public static void main(String[] args) {
        new Task().run();
    }

    static long timeBegin = System.currentTimeMillis();
    static FastScanner sc;
    static PrintWriter out;
    static PrintStream err = System.err;
}
//</editor-fold>

//<editor-fold defaultstate="collapsed" desc="FastScanner">
class FastScanner {

    BufferedReader br;
    StringTokenizer st;

    FastScanner(InputStreamReader reader) {
        br = new BufferedReader(reader);
        st = new StringTokenizer("");
    }

    String next() {
        while (!st.hasMoreElements()) {
            try {
                st = new StringTokenizer(br.readLine());
            } catch (IOException ex) {
                Task.MLE();
            }
        }
        return st.nextToken();
    }

    int nextInt() {
        return Integer.parseInt(next());
    }

    long nextLong() {
        return Long.parseLong(next());
    }
    double nextDouble() {
        return Double.parseDouble(next());
    }
}
//</editor-fold>

class Solver {
    void ass(boolean OK) { if(!OK)Task.MLE(); }

    FastScanner sc;
    PrintWriter out;
    static PrintStream err = System.err;

    final int mod = (int)1e9 + 7;
    int[] str;
    long[] val, len;
    int q;
    int[] from;
    int[][] to;

    long pow10Mod( long p ){
        if( p == 0 ) return 1;
        long ans = pow10Mod(p/2);
        ans = (ans * ans) % mod;
        if( p%2==1 ) ans = (ans * 10) % mod;
        return ans;
    }

    void solve(){
        {
            String s = sc.next();
            str = new int[s.length()];
            for (int i = 0; i < s.length(); i++)
                str[i] = s.charAt(i) - '0';
        }

        val = new long[10];
        len = new long[10];
        for (int i = 0; i <= 9; i++) {
            val[i] = i;
            len[i] = 1;
        }

        q = sc.nextInt();
        from = new int[q];
        to = new int[q][];
        for (int i = 0; i < q; i++) {
            String s;
            try {
                s = sc.br.readLine();
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException();
            }
            int pos = s.indexOf("->");
            String[] arr = { s.substring(0,pos), s.substring(pos+2) };
            from[i] = Integer.parseInt(arr[0].trim());
            arr[1] = arr[1].trim();
            to[i] = new int[arr[1].length()];
            for (int j = 0; j < arr[1].length(); j++)
                to[i][j] = arr[1].charAt(j) - '0';
        }

        for( int i = q-1; 0 <= i; --i ){
            long newVal = 0, newLen = 0;
            for( int j = to[i].length-1; 0 <= j; --j ){
                int x = to[i][j];
                newVal = (newVal + val[x] * pow10Mod(newLen)) % mod;
                newLen += len[x];
            }
            val[from[i]] = newVal;
            len[from[i]] = newLen;
        }

        long ans = 0, len = 0;
        for (int i = str.length-1; 0 <= i; --i) {
            int x = str[i];
            ans = (ans + val[x]*pow10Mod(len)) % mod;
            len += this.len[x];
        }
        out.println( ans );
    }

}


import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import java.math.BigInteger;
import static java.math.BigInteger.*;
import static java.util.Arrays.*;
import javax.xml.ws.Holder;

//<editor-fold defaultstate="collapsed" desc="Main">
public class Task{
// https://netbeans.org/kb/73/java/editor-codereference_ru.html#display
    private void run() {
        try {
            Locale.setDefault(Locale.US);
        } catch (Exception e) {
        }
        boolean oj = true;
        try {
            oj = System.getProperty("MYLOCAL") == null;
        } catch (Exception e) {
        }

        if (oj) {
            sc = new FastScanner(new InputStreamReader(System.in));
            out = new PrintWriter(new OutputStreamWriter(System.out));
        } else {
            try {
                sc = new FastScanner(new FileReader("input.txt"));
                out = new PrintWriter(new FileWriter("output.txt"));
            } catch (IOException e) {
                MLE();
            }
        }
        Solver s = new Solver();
        s.sc = sc;
        s.out = out;
        s.solve();
        if (!oj) {
            err.println("Time: " + (System.currentTimeMillis() - timeBegin) / 1e3);
            err.printf("Mem: %d\n", (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) >> 20);
        }
        out.flush();
    }

    private void show(int[] arr) {
        for (int v : arr) {
            err.print(" " + v);
        }
        err.println();
    }

    public static void exit() {
        err.println("Time: " + (System.currentTimeMillis() - timeBegin) / 1e3);
        out.flush();
        out.close();
        System.exit(0);
    }

    public static void MLE() {
        int[][] arr = new int[1024 * 1024][];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = new int[1024 * 1024];
        }
    }

    public static void main(String[] args) {
        new Task().run();
    }

    static long timeBegin = System.currentTimeMillis();
    static FastScanner sc;
    static PrintWriter out;
    static PrintStream err = System.err;
}
//</editor-fold>

//<editor-fold defaultstate="collapsed" desc="FastScanner">
class FastScanner {

    BufferedReader br;
    StringTokenizer st;

    FastScanner(InputStreamReader reader) {
        br = new BufferedReader(reader);
        st = new StringTokenizer("");
    }

    String next() {
        while (!st.hasMoreElements()) {
            try {
                st = new StringTokenizer(br.readLine());
            } catch (IOException ex) {
                Task.MLE();
            }
        }
        return st.nextToken();
    }

    int nextInt() {
        return Integer.parseInt(next());
    }

    long nextLong() {
        return Long.parseLong(next());
    }
    double nextDouble() {
        return Double.parseDouble(next());
    }
}
//</editor-fold>

class Solver {
    void ass(boolean OK) { if(!OK)Task.MLE(); }

    FastScanner sc;
    PrintWriter out;
    static PrintStream err = System.err;

    final int mod = (int)1e9 + 7;
    final int mod1 = mod - 1;
    int[] str;
    long[] val, len;
    int q;
    int[] from;
    int[][] to;

    long pow10Mod( long p ){
        if( p < 0 ) Task.MLE();
        if( p == 0 ) return 1;
        long ans = pow10Mod(p/2);
        ans = (ans * ans) % mod;
        if( p%2==1 ) ans = (ans * 10) % mod;
        return ans;
    }

    void solve(){
        {
            String s = sc.next();
            str = new int[s.length()];
            for (int i = 0; i < s.length(); i++)
                str[i] = s.charAt(i) - '0';
        }

        val = new long[10];
        len = new long[10];
        for (int i = 0; i <= 9; i++) {
            val[i] = i;
            len[i] = 1;
        }

        q = sc.nextInt();
        from = new int[q];
        to = new int[q][];
        for (int i = 0; i < q; i++) {
            String s;
            try {
                s = sc.br.readLine();
            } catch (IOException e) {
                throw new RuntimeException();
            }
            int pos = s.indexOf("->");
            String[] arr = { s.substring(0,pos), s.substring(pos+2) };
            from[i] = Integer.parseInt(arr[0].trim());
            arr[1] = arr[1].trim();
            to[i] = new int[arr[1].length()];
            for (int j = 0; j < arr[1].length(); j++)
                to[i][j] = arr[1].charAt(j) - '0';
        }

        for( int i = q-1; 0 <= i; --i ){
            long newVal = 0, newLen = 0;
            for( int j = to[i].length-1; 0 <= j; --j ){
                int x = to[i][j];
                newVal = (newVal + val[x] * pow10Mod(newLen)%mod) % mod;
                newLen = (newLen + len[x]) % mod1;
            }
            val[from[i]] = newVal;
            len[from[i]] = newLen;
        }

        long ans = 0, len = 0;
        for (int i = str.length-1; 0 <= i; --i) {
            int x = str[i];
            ans = (ans + val[x]*pow10Mod(len)%mod) % mod;
            len = (len + this.len[x]) % mod1;
        }
        out.println( ans );
    }

}


import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import java.math.BigInteger;
import static java.math.BigInteger.*;
import static java.util.Arrays.*;
import javax.xml.ws.Holder;

//<editor-fold defaultstate="collapsed" desc="Main">
public class Task{
// https://netbeans.org/kb/73/java/editor-codereference_ru.html#display
    private void run() {
        try {
            Locale.setDefault(Locale.US);
        } catch (Exception e) {
        }
        boolean oj = true;
        try {
            oj = System.getProperty("MYLOCAL") == null;
        } catch (Exception e) {
        }

        if (oj) {
            sc = new FastScanner(new InputStreamReader(System.in));
            out = new PrintWriter(new OutputStreamWriter(System.out));
        } else {
            try {
                sc = new FastScanner(new FileReader("input.txt"));
                out = new PrintWriter(new FileWriter("output.txt"));
            } catch (IOException e) {
                MLE();
            }
        }
        Solver s = new Solver();
        s.sc = sc;
        s.out = out;
        s.solve();
        if (!oj) {
            err.println("Time: " + (System.currentTimeMillis() - timeBegin) / 1e3);
            err.printf("Mem: %d\n", (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) >> 20);
        }
        out.flush();
    }

    private void show(int[] arr) {
        for (int v : arr) {
            err.print(" " + v);
        }
        err.println();
    }

    public static void exit() {
        err.println("Time: " + (System.currentTimeMillis() - timeBegin) / 1e3);
        out.flush();
        out.close();
        System.exit(0);
    }

    public static void MLE() {
        int[][] arr = new int[1024 * 1024][];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = new int[1024 * 1024];
        }
    }

    public static void main(String[] args) {
        new Task().run();
    }

    static long timeBegin = System.currentTimeMillis();
    static FastScanner sc;
    static PrintWriter out;
    static PrintStream err = System.err;
}
//</editor-fold>

//<editor-fold defaultstate="collapsed" desc="FastScanner">
class FastScanner {

    BufferedReader br;
    StringTokenizer st;

    FastScanner(InputStreamReader reader) {
        br = new BufferedReader(reader);
        st = new StringTokenizer("");
    }

    String next() {
        while (!st.hasMoreElements()) {
            try {
                st = new StringTokenizer(br.readLine());
            } catch (IOException ex) {
                Task.MLE();
            }
        }
        return st.nextToken();
    }

    int nextInt() {
        return Integer.parseInt(next());
    }

    long nextLong() {
        return Long.parseLong(next());
    }
    double nextDouble() {
        return Double.parseDouble(next());
    }
}
//</editor-fold>

class Solver {
    void ass(boolean OK) { if(!OK)Task.MLE(); }

    FastScanner sc;
    PrintWriter out;
    static PrintStream err = System.err;

    final int mod = (int)1e9 + 7;
    final int mod1 = (int)1e9 + 7;
    int[] str;
    long[] val, len;
    int q;
    int[] from;
    int[][] to;

    long pow10Mod( long p ){
        if( p < 0 ) Task.MLE();
        if( p == 0 ) return 1;
        long ans = pow10Mod(p/2);
        ans = (ans * ans) % mod;
        if( p%2==1 ) ans = (ans * 10) % mod;
        return ans;
    }

    void solve(){
        {
            String s = sc.next();
            str = new int[s.length()];
            for (int i = 0; i < s.length(); i++)
                str[i] = s.charAt(i) - '0';
        }

        val = new long[10];
        len = new long[10];
        for (int i = 0; i <= 9; i++) {
            val[i] = i;
            len[i] = 1;
        }

        q = sc.nextInt();
        from = new int[q];
        to = new int[q][];
        for (int i = 0; i < q; i++) {
            String s;
            try {
                s = sc.br.readLine();
            } catch (IOException e) {
                throw new RuntimeException();
            }
            int pos = s.indexOf("->");
            String[] arr = { s.substring(0,pos), s.substring(pos+2) };
            from[i] = Integer.parseInt(arr[0].trim());
            arr[1] = arr[1].trim();
            to[i] = new int[arr[1].length()];
            for (int j = 0; j < arr[1].length(); j++)
                to[i][j] = arr[1].charAt(j) - '0';
        }

        for( int i = q-1; 0 <= i; --i ){
            long newVal = 0, newLen = 0;
            for( int j = to[i].length-1; 0 <= j; --j ){
                int x = to[i][j];
                newVal = (newVal + val[x] * pow10Mod(newLen)%mod) % mod;
                newLen = (newLen + len[x]) % mod1;
            }
            val[from[i]] = newVal;
            len[from[i]] = newLen;
        }

        long ans = 0, len = 0;
        for (int i = str.length-1; 0 <= i; --i) {
            int x = str[i];
            ans = (ans + val[x]*pow10Mod(len)%mod) % mod;
            len = (len + this.len[x]) % mod1;
        }
        out.println( ans );
    }

}


import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import java.math.BigInteger;
import static java.math.BigInteger.*;
import static java.util.Arrays.*;
import javax.xml.ws.Holder;

//<editor-fold defaultstate="collapsed" desc="Main">
public class Task{
// https://netbeans.org/kb/73/java/editor-codereference_ru.html#display
    private void run() {
        try {
            Locale.setDefault(Locale.US);
        } catch (Exception e) {
        }
        boolean oj = true;
        try {
            oj = System.getProperty("MYLOCAL") == null;
        } catch (Exception e) {
        }

        if (oj) {
            sc = new FastScanner(new InputStreamReader(System.in));
            out = new PrintWriter(new OutputStreamWriter(System.out));
        } else {
            try {
                sc = new FastScanner(new FileReader("input.txt"));
                out = new PrintWriter(new FileWriter("output.txt"));
            } catch (IOException e) {
                MLE();
            }
        }
        Solver s = new Solver();
        s.sc = sc;
        s.out = out;
        s.solve();
        if (!oj) {
            err.println("Time: " + (System.currentTimeMillis() - timeBegin) / 1e3);
            err.printf("Mem: %d\n", (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) >> 20);
        }
        out.flush();
    }

    private void show(int[] arr) {
        for (int v : arr) {
            err.print(" " + v);
        }
        err.println();
    }

    public static void exit() {
        err.println("Time: " + (System.currentTimeMillis() - timeBegin) / 1e3);
        out.flush();
        out.close();
        System.exit(0);
    }

    public static void MLE() {
        int[][] arr = new int[1024 * 1024][];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = new int[1024 * 1024];
        }
    }

    public static void main(String[] args) {
        new Task().run();
    }

    static long timeBegin = System.currentTimeMillis();
    static FastScanner sc;
    static PrintWriter out;
    static PrintStream err = System.err;
}
//</editor-fold>

//<editor-fold defaultstate="collapsed" desc="FastScanner">
class FastScanner {

    BufferedReader br;
    StringTokenizer st;

    FastScanner(InputStreamReader reader) {
        br = new BufferedReader(reader);
        st = new StringTokenizer("");
    }

    String next() {
        while (!st.hasMoreElements()) {
            try {
                st = new StringTokenizer(br.readLine());
            } catch (IOException ex) {
                Task.MLE();
            }
        }
        return st.nextToken();
    }

    int nextInt() {
        return Integer.parseInt(next());
    }

    long nextLong() {
        return Long.parseLong(next());
    }
    double nextDouble() {
        return Double.parseDouble(next());
    }
}
//</editor-fold>

class Solver {
    void ass(boolean OK) { if(!OK)Task.MLE(); }

    FastScanner sc;
    PrintWriter out;
    static PrintStream err = System.err;

    final int mod = (int)1e9 + 7;
    int[] str;
    long[] val, len;
    int q;
    int[] from;
    int[][] to;

    long pow10Mod( long p ){
        if( p == 0 ) return 1;
        long ans = pow10Mod(p/2);
        ans = (ans * ans) % mod;
        if( p%2==1 ) ans = (ans * 10) % mod;
        return ans;
    }

    void solve(){
        {
            String s = sc.next();
            str = new int[s.length()];
            for (int i = 0; i < s.length(); i++)
                str[i] = s.charAt(i) - '0';
        }

        val = new long[10];
        len = new long[10];
        for (int i = 0; i <= 9; i++) {
            val[i] = i;
            len[i] = 1;
        }

        q = sc.nextInt();
        from = new int[q];
        to = new int[q][];
        for (int i = 0; i < q; i++) {
            String s;
            try {
                s = sc.br.readLine();
            } catch (IOException e) {
                throw new RuntimeException();
            }
            int pos = s.indexOf("->");
            String[] arr = { s.substring(0,pos), s.substring(pos+2) };
            from[i] = Integer.parseInt(arr[0].trim());
            arr[1] = arr[1].trim();
            to[i] = new int[arr[1].length()];
            for (int j = 0; j < arr[1].length(); j++)
                to[i][j] = arr[1].charAt(j) - '0';
        }

        for( int i = q-1; 0 <= i; --i ){
            long newVal = 0, newLen = 0;
            for( int j = to[i].length-1; 0 <= j; --j ){
                int x = to[i][j];
                newVal = (newVal + val[x] * pow10Mod(newLen)%mod) % mod;
                newLen += len[x];
            }
            val[from[i]] = newVal;
            len[from[i]] = newLen;
        }

        long ans = 0, len = 0;
        for (int i = str.length-1; 0 <= i; --i) {
            int x = str[i];
            ans = (ans + val[x]*pow10Mod(len)%mod) % mod;
            len += this.len[x];
        }
        out.println( ans );
    }

}


import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import java.math.BigInteger;
import static java.math.BigInteger.*;
import static java.util.Arrays.*;
import javax.xml.ws.Holder;

//<editor-fold defaultstate="collapsed" desc="Main">
public class Task{
// https://netbeans.org/kb/73/java/editor-codereference_ru.html#display
    private void run() {
        try {
            Locale.setDefault(Locale.US);
        } catch (Exception e) {
        }
        boolean oj = true;
        try {
            oj = System.getProperty("MYLOCAL") == null;
        } catch (Exception e) {
        }

//        if (oj) {
//            sc = new FastScanner(new InputStreamReader(System.in));
//            out = new PrintWriter(new OutputStreamWriter(System.out));
//        } else {
            try {
                sc = new FastScanner(new FileReader("input.txt"));
                out = new PrintWriter(new FileWriter("output.txt"));
            } catch (IOException e) {
                MLE();
            }
//        }
        Solver s = new Solver();
        s.sc = sc;
        s.out = out;
        s.solve();
        if (!oj) {
            err.println("Time: " + (System.currentTimeMillis() - timeBegin) / 1e3);
            err.printf("Mem: %d\n", (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) >> 20);
        }
        out.flush();
    }

    private void show(int[] arr) {
        for (int v : arr) {
            err.print(" " + v);
        }
        err.println();
    }

    public static void exit() {
        err.println("Time: " + (System.currentTimeMillis() - timeBegin) / 1e3);
        out.flush();
        out.close();
        System.exit(0);
    }

    public static void MLE() {
        int[][] arr = new int[1024 * 1024][];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = new int[1024 * 1024];
        }
    }

    public static void main(String[] args) {
        new Task().run();
    }

    static long timeBegin = System.currentTimeMillis();
    static FastScanner sc;
    static PrintWriter out;
    static PrintStream err = System.err;
}
//</editor-fold>

//<editor-fold defaultstate="collapsed" desc="FastScanner">
class FastScanner {

    BufferedReader br;
    StringTokenizer st;

    FastScanner(InputStreamReader reader) {
        br = new BufferedReader(reader);
        st = new StringTokenizer("");
    }

    String next() {
        while (!st.hasMoreElements()) {
            try {
                st = new StringTokenizer(br.readLine());
            } catch (IOException ex) {
                Task.MLE();
            }
        }
        return st.nextToken();
    }

    int nextInt() {
        return Integer.parseInt(next());
    }

    long nextLong() {
        return Long.parseLong(next());
    }
    double nextDouble() {
        return Double.parseDouble(next());
    }
}
//</editor-fold>

class Solver {
    void ass(boolean OK) { if(!OK)Task.MLE(); }

    FastScanner sc;
    PrintWriter out;
    static PrintStream err = System.err;

    final int mod = (int)1e9 + 7;
    int[] str;
    long[] val;
    int[] len;
    int q;
    int[] from;
    int[][] to;
    long[] pow10 = new long[(int)1e5 + 100];
    {
        pow10[0] = 1;
        for (int i = 1; i < pow10.length; i++)
            pow10[i] = 10 * pow10[i-1] % mod;
    }

    void solve(){
        {
            String s = sc.next();
            str = new int[s.length()];
            for (int i = 0; i < s.length(); i++)
                str[i] = s.charAt(i) - '0';
        }

        val = new long[10];
        len = new int[10];
        for (int i = 0; i <= 9; i++) {
            val[i] = i;
            len[i] = 1;
        }

        q = sc.nextInt();
        from = new int[q];
        to = new int[q][];
        for (int i = 0; i < q; i++) {
            String s;
            try {
                s = sc.br.readLine();
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException();
            }
            int pos = s.indexOf("->");
            String[] arr = { s.substring(0,pos), s.substring(pos+2) };
            from[i] = Integer.parseInt(arr[0].trim());
            arr[1] = arr[1].trim();
            to[i] = new int[arr[1].length()];
            for (int j = 0; j < arr[1].length(); j++)
                to[i][j] = arr[1].charAt(j) - '0';
        }

        for( int i = q-1; 0 <= i; --i ){
            long newVal = 0;
            int newLen = 0;
            for( int j = to[i].length-1; 0 <= j; --j ){
                int x = to[i][j];
                newVal += val[x] * pow10[newLen] % mod;
                newVal %= mod;
                newLen += len[x];
            }
            val[from[i]] = newVal;
            len[from[i]] = newLen;
        }

        long ans = 0;
        int len = 0;
        for (int i = str.length-1; 0 <= i; --i) {
            int x = str[i];
            ans = (ans + val[x]*pow10[len]) % mod;
            len += this.len[x];
        }
        out.println( ans );
    }

}


import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import java.math.BigInteger;
import static java.math.BigInteger.*;
import static java.util.Arrays.*;
import javax.xml.ws.Holder;

//<editor-fold defaultstate="collapsed" desc="Main">
public class Task{
// https://netbeans.org/kb/73/java/editor-codereference_ru.html#display
    private void run() {
        try {
            Locale.setDefault(Locale.US)
;
        } catch (Exception e) {
        }
        boolean oj = true;
        try {
            oj = System.getProperty("MYLOCAL") == null;
        } catch (Exception e) {
        }

        if (oj) {
            sc = new FastScanner(new InputStreamReader(System.in));
            out = new PrintWriter(new OutputStreamWriter(System.out));
        } else {
            try {
                sc = new FastScanner(new FileReader("input.txt"));
                out = new PrintWriter(new FileWriter("output.txt"));
            } catch (IOException e) {
                MLE();
            }
        }
        Solver s = new Solver();
        s.sc = sc;
        s.out = out;
        s.solve();
        if (!oj) {
            err.println("Time: " + (System.currentTimeMillis() - timeBegin) / 1e3);
            err.printf("Mem: %d\n", (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) >> 20);
        }
        out.flush();
    }

    private void show(int[] arr) {
        for (int v : arr) {
            err.print(" " + v);
        }
        err.println();
    }

    public static void exit() {
        err.println("Time: " + (System.currentTimeMillis() - timeBegin) / 1e3);
        out.flush();
        out.close();
        System.exit(0);
    }

    public static void MLE() {
        int[][] arr = new int[1024 * 1024][];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = new int[1024 * 1024];
        }
    }

    public static void main(String[] args) {
        new Task().run();
    }

    static long timeBegin = System.currentTimeMillis();
    static FastScanner sc;
    static PrintWriter out;
    static PrintStream err = System.err;
}
//</editor-fold>

//<editor-fold defaultstate="collapsed" desc="FastScanner">
class FastScanner {

    BufferedReader br;
    StringTokenizer st;

    FastScanner(InputStreamReader reader) {
        br = new BufferedReader(reader);
        st = new StringTokenizer("");
    }

    String next() {
        while (!st.hasMoreElements()) {
            try {
                st = new StringTokenizer(br.readLine());
            } catch (IOException ex) {
                Task.MLE();
            }
        }
        return st.nextToken();
    }

    int nextInt() {
        return Integer.parseInt(next());
    }

    long nextLong() {
        return Long.parseLong(next());
    }
    double nextDouble() {
        return Double.parseDouble(next());
    }
}
//</editor-fold>

class Solver {
    void ass(boolean OK) { if(!OK)Task.MLE(); }

    FastScanner sc;
    PrintWriter out;
    static PrintStream err = System.err;

    final int mod = (int)1e9 + 7;
    int[] str;
    long[] val, len;
    int q;
    int[] from;
    int[][] to;

    long pow10Mod( long p ){
        if( p < 0 ) Task.MLE();
        if( p == 0 ) return 1;
        long ans = pow10Mod(p/2);
        ans = (ans * ans) % mod;
        if( p%2==1 ) ans = (ans * 10) % mod;
        return ans;
    }

    void solve(){
        {
            String s = sc.next();
            str = new int[s.length()];
            for (int i = 0; i < s.length(); i++)
                str[i] = s.charAt(i) - '0';
        }

        val = new long[10];
        len = new long[10];
        for (int i = 0; i <= 9; i++) {
            val[i] = i;
            len[i] = 1;
        }

        q = sc.nextInt();
        from = new int[q];
        to = new int[q][];
        for (int i = 0; i < q; i++) {
            String s;
            try {
                s = sc.br.readLine();
            } catch (IOException e) {
                throw new RuntimeException();
            }
            int pos = s.indexOf("->");
            String[] arr = { s.substring(0,pos), s.substring(pos+2) };
            from[i] = Integer.parseInt(arr[0].trim());
            arr[1] = arr[1].trim();
            to[i] = new int[arr[1].length()];
            for (int j = 0; j < arr[1].length(); j++)
                to[i][j] = arr[1].charAt(j) - '0';
        }

        for( int i = q-1; 0 <= i; --i ){
            long newVal = 0, newLen = 0;
            for( int j = to[i].length-1; 0 <= j; --j ){
                int x = to[i][j];
                newVal = (newVal + val[x] * pow10Mod(newLen)%mod) % mod;
                newLen += len[x];
            }
            val[from[i]] = newVal;
            len[from[i]] = newLen;
        }

        long ans = 0, len = 0;
        for (int i = str.length-1; 0 <= i; --i) {
            int x = str[i];
            ans = (ans + val[x]*pow10Mod(len)%mod) % mod;
            len += this.len[x];
        }
        out.println( ans );
    }

}


import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import java.math.BigInteger;
import static java.math.BigInteger.*;
import static java.util.Arrays.*;
import javax.xml.ws.Holder;

//<editor-fold defaultstate="collapsed" desc="Main">
public class Task{
// https://netbeans.org/kb/73/java/editor-codereference_ru.html#display
    private void run() {
        try {
            Locale.setDefault(Locale.US);
        } catch (Exception e) {
        }
        boolean oj = true;
        try {
            oj = System.getProperty("MYLOCAL") == null;
        } catch (Exception e) {
        }

        if (oj) {
            sc = new FastScanner(new InputStreamReader(System.in));
            out = new PrintWriter(new OutputStreamWriter(System.out));
        } else {
            try {
                sc = new FastScanner(new FileReader("input.txt"));
                out = new PrintWriter(new FileWriter("output.txt"));
            } catch (IOException e) {
                MLE();
            }
        }
        Solver s = new Solver();
        s.sc = sc;
        s.out = out;
        s.solve();
        if (!oj) {
            err.println("Time: " + (System.currentTimeMillis() - timeBegin) / 1e3);
            err.printf("Mem: %d\n", (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) >> 20);
        }
        out.flush();
    }

    private void show(int[] arr) {
        for (int v : arr) {
            err.print(" " + v);
        }
        err.println();
    }

    public static void exit() {
        err.println("Time: " + (System.currentTimeMillis() - timeBegin) / 1e3);
        out.flush();
        out.close();
        System.exit(0);
    }

    public static void MLE() {
        int[][] arr = new int[1024 * 1024][];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = new int[1024 * 1024];
        }
    }

    public static void main(String[] args) {
        new Task().run();
    }

    static long timeBegin = System.currentTimeMillis();
    static FastScanner sc;
    static PrintWriter out;
    static PrintStream err = System.err;
}
//</editor-fold>

//<editor-fold defaultstate="collapsed" desc="FastScanner">
class FastScanner {

    BufferedReader br;
    StringTokenizer st;

    FastScanner(InputStreamReader reader) {
        br = new BufferedReader(reader);
        st = new StringTokenizer("");
    }

    String next() {
        while (!st.hasMoreElements()) {
            try {
                st = new StringTokenizer(br.readLine());
            } catch (IOException ex) {
                Task.MLE();
            }
        }
        return st.nextToken();
    }

    int nextInt() {
        return Integer.parseInt(next());
    }

    long nextLong() {
        return Long.parseLong(next());
    }
    double nextDouble() {
        return Double.parseDouble(next());
    }
}
//</editor-fold>

class Solver {
    void ass(boolean OK) { if(!OK)Task.MLE(); }

    FastScanner sc;
    PrintWriter out;
    static PrintStream err = System.err;

    final int mod = (int)1e9 + 7;
    int[] str;
    long[] val;
    int[] len;
    int q;
    int[] from;
    int[][] to;

    long pow10Mod( long p ){
        if( p == 0 ) return 1;
        long ans = pow10Mod(p/2);
        ans = (ans * ans) % mod;
        if( p%2==1 ) ans = (ans * 10) % mod;
        return ans;
    }

    void solve(){
        {
            String s = sc.next();
            str = new int[s.length()];
            for (int i = 0; i < s.length(); i++)
                str[i] = s.charAt(i) - '0';
        }

        val = new long[10];
        len = new int[10];
        for (int i = 0; i <= 9; i++) {
            val[i] = i;
            len[i] = 1;
        }

        q = sc.nextInt();
        from = new int[q];
        to = new int[q][];
        for (int i = 0; i < q; i++) {
            String s;
            try {
                s = sc.br.readLine();
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException();
            }
            int pos = s.indexOf("->");
            String[] arr = { s.substring(0,pos), s.substring(pos+2) };
            from[i] = Integer.parseInt(arr[0].trim());
            arr[1] = arr[1].trim();
            to[i] = new int[arr[1].length()];
            for (int j = 0; j < arr[1].length(); j++)
                to[i][j] = arr[1].charAt(j) - '0';
        }

        for( int i = q-1; 0 <= i; --i ){
            long newVal = 0;
            int newLen = 0;
            for( int j = to[i].length-1; 0 <= j; --j ){
                int x = to[i][j];
                newVal += val[x] * pow10Mod(newLen) % mod;
                newVal %= mod;
                newLen += len[x];
            }
            val[from[i]] = newVal;
            len[from[i]] = newLen;
        }

        long ans = 0;
        int len = 0;
        for (int i = str.length-1; 0 <= i; --i) {
            int x = str[i];
            ans = (ans + val[x]*pow10Mod(len)) % mod;
            len += this.len[x];
        }
        out.println( ans );
    }

}


import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import java.math.BigInteger;
import static java.math.BigInteger.*;
import static java.util.Arrays.*;
import javax.xml.ws.Holder;

//<editor-fold defaultstate="collapsed" desc="Main">
public class Task{
// https://netbeans.org/kb/73/java/editor-codereference_ru.html#display
    private void run() {
        try {
            Locale.setDefault(Locale.US);
        } catch (Exception e) {
        }
        boolean oj = true;
        try {
            oj = System.getProperty("MYLOCAL") == null;
        } catch (Exception e) {
        }

        if (oj) {
            sc = new FastScanner(new InputStreamReader(System.in));
            out = new PrintWriter(new OutputStreamWriter(System.out));
        } else {
            try {
                sc = new FastScanner(new FileReader("input.txt"));
                out = new PrintWriter(new FileWriter("output.txt"));
            } catch (IOException e) {
                MLE();
            }
        }
        Solver s = new Solver();
        s.sc = sc;
        s.out = out;
        s.solve();
        if (!oj) {
            err.println("Time: " + (System.currentTimeMillis() - timeBegin) / 1e3);
            err.printf("Mem: %d\n", (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) >> 20);
        }
        out.flush();
    }

    private void show(int[] arr) {
        for (int v : arr) {
            err.print(" " + v);
        }
        err.println();
    }

    public static void exit() {
        err.println("Time: " + (System.currentTimeMillis() - timeBegin) / 1e3);
        out.flush();
        out.close();
        System.exit(0);
    }

    public static void MLE() {
        int[][] arr = new int[1024 * 1024][];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = new int[1024 * 1024];
        }
    }

    public static void main(String[] args) {
        new Task().run();
    }

    static long timeBegin = System.currentTimeMillis();
    static FastScanner sc;
    static PrintWriter out;
    static PrintStream err = System.err;
}
//</editor-fold>

//<editor-fold defaultstate="collapsed" desc="FastScanner">
class FastScanner {

    BufferedReader br;
    StringTokenizer st;

    FastScanner(InputStreamReader reader) {
        br = new BufferedReader(reader);
        st = new StringTokenizer("");
    }

    String next() {
        while (!st.hasMoreElements()) {
            try {
                st = new StringTokenizer(br.readLine());
            } catch (IOException ex) {
                Task.MLE();
            }
        }
        return st.nextToken();
    }

    int nextInt() {
        return Integer.parseInt(next());
    }

    long nextLong() {
        return Long.parseLong(next());
    }
    double nextDouble() {
        return Double.parseDouble(next());
    }
}
//</editor-fold>

class Solver {
    void ass(boolean OK) { if(!OK)Task.MLE(); }

    FastScanner sc;
    PrintWriter out;
    static PrintStream err = System.err;

    final int mod = (int)1e9 + 7;
    int[] str;
    long[] val;
    long[] len;
    int q;
    int[] from;
    int[][] to;

    long pow10Mod( long p ){
        if( p == 0 ) return 1;
        long ans = pow10Mod(p/2);
        ans = (ans * ans) % mod;
        if( p%2==1 ) ans = (ans * 10) % mod;
        return ans;
    }

    void solve(){
        {
            String s = sc.next();
            str = new int[s.length()];
            for (int i = 0; i < s.length(); i++)
                str[i] = s.charAt(i) - '0';
        }

        val = new long[10];
        len = new long[10];
        for (int i = 0; i <= 9; i++) {
            val[i] = i;
            len[i] = 1;
        }

        q = sc.nextInt();
        from = new int[q];
        to = new int[q][];
        for (int i = 0; i < q; i++) {
            String s;
            try {
                s = sc.br.readLine();
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException();
            }
            int pos = s.indexOf("->");
            String[] arr = { s.substring(0,pos), s.substring(pos+2) };
            from[i] = Integer.parseInt(arr[0].trim());
            arr[1] = arr[1].trim();
            to[i] = new int[arr[1].length()];
            for (int j = 0; j < arr[1].length(); j++)
                to[i][j] = arr[1].charAt(j) - '0';
        }

        for( int i = q-1; 0 <= i; --i ){
            long newVal = 0;
            long newLen = 0;
            for( int j = to[i].length-1; 0 <= j; --j ){
                int x = to[i][j];
                newVal += val[x] * pow10Mod(newLen) % mod;
                newVal %= mod;
                newLen += len[x];
            }
            val[from[i]] = newVal;
            len[from[i]] = newLen;
        }

        long ans = 0;
        long len = 0;
        for (int i = str.length-1; 0 <= i; --i) {
            int x = str[i];
            ans = (ans + val[x]*pow10Mod(len)) % mod;
            len += this.len[x];
        }
        out.println( ans );
    }

}


import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import java.math.BigInteger;
import static java.math.BigInteger.*;
import static java.util.Arrays.*;
import javax.xml.ws.Holder;

//<editor-fold defaultstate="collapsed" desc="Main">
public class Task{
// https://netbeans.org/kb/73/java/editor-codereference_ru.html#display
    private void run() {
        try {
            Locale.setDefault(Locale.US);
        } catch (Exception e) {
        }
        boolean oj = true;
        try {
            oj = System.getProperty("MYLOCAL") == null;
        } catch (Exception e) {
        }

        if (oj) {
            sc = new FastScanner(new InputStreamReader(System.in));
            out = new PrintWriter(new OutputStreamWriter(System.out));
        } else {
            try {
                sc = new FastScanner(new FileReader("input.txt"));
                out = new PrintWriter(new FileWriter("output.txt"));
            } catch (IOException e) {
                MLE();
            }
        }
        Solver s = new Solver();
        s.sc = sc;
        s.out = out;
        s.solve();
        if (!oj) {
            err.println("Time: " + (System.currentTimeMillis() - timeBegin) / 1e3);
            err.printf("Mem: %d\n", (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) >> 20);
        }
        out.flush();
    }

    private void show(int[] arr) {
        for (int v : arr) {
            err.print(" " + v);
        }
        err.println();
    }

    public static void exit() {
        err.println("Time: " + (System.currentTimeMillis() - timeBegin) / 1e3);
        out.flush();
        out.close();
        System.exit(0);
    }

    public static void MLE() {
        int[][] arr = new int[1024 * 1024][];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = new int[1024 * 1024];
        }
    }

    public static void main(String[] args) {
        new Task().run();
    }

    static long timeBegin = System.currentTimeMillis();
    static FastScanner sc;
    static PrintWriter out;
    static PrintStream err = System.err;
}
//</editor-fold>

//<editor-fold defaultstate="collapsed" desc="FastScanner">
class FastScanner {

    BufferedReader br;
    StringTokenizer st;

    FastScanner(InputStreamReader reader) {
        br = new BufferedReader(reader);
        st = new StringTokenizer("");
    }

    String next() {
        while (!st.hasMoreElements()) {
            try {
                st = new StringTokenizer(br.readLine());
            } catch (IOException ex) {
                Task.MLE();
            }
        }
        return st.nextToken();
    }

    int nextInt() {
        return Integer.parseInt(next());
    }

    long nextLong() {
        return Long.parseLong(next());
    }
    double nextDouble() {
        return Double.parseDouble(next());
    }
}
//</editor-fold>

class Solver {
    void ass(boolean OK) { if(!OK)Task.MLE(); }

    FastScanner sc;
    PrintWriter out;
    static PrintStream err = System.err;

    final int mod = (int)1e9 + 7;
    int[] str;
    long[] val, len;
    int q;
    int[] from;
    int[][] to;

    long pow10Mod( long p ){
        if( p < 0 ) Task.MLE();
        if( p == 0 ) return 1;
        long ans = pow10Mod(p/2);
        ans = (ans * ans) % mod;
        if( p%2==1 ) ans = (ans * 10) % mod;
        return ans;
    }

    void solve(){
        {
            String s = sc.next();
            str = new int[s.length()];
            for (int i = 0; i < s.length(); i++)
                str[i] = s.charAt(i) - '0';
        }

        val = new long[10];
        len = new long[10];
        for (int i = 0; i <= 9; i++) {
            val[i] = i;
            len[i] = 1;
        }

        q = sc.nextInt();
        from = new int[q];
        to = new int[q][];
        for (int i = 0; i < q; i++) {
            String s;
            try {
                s = sc.br.readLine();
            } catch (IOException e) {
                throw new RuntimeException();
            }
            int pos = s.indexOf("->");
            String[] arr = { s.substring(0,pos), s.substring(pos+2) };
            from[i] = Integer.parseInt(arr[0].trim());
            arr[1] = arr[1].trim();
            to[i] = new int[arr[1].length()];
            for (int j = 0; j < arr[1].length(); j++)
                to[i][j] = arr[1].charAt(j) - '0';
        }

        for( int i = q-1; 0 <= i; --i ){
            long newVal = 0, newLen = 0;
            for( int j = to[i].length-1; 0 <= j; --j ){
                int x = to[i][j];
                newVal = (newVal + val[x] * pow10Mod(newLen)%mod) % mod;
                newLen += len[x];
            }
            val[from[i]] = newVal;
            len[from[i]] = newLen;
        }

        long ans = 0, len = 0;
        for (int i = str.length-1; 0 <= i; --i) {
            int x = str[i];
            ans = (ans + val[x]*pow10Mod(len)%mod) % mod;
            len += this.len[x];
        }
        out.println( ans );
    }

}


import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import java.math.BigInteger;
import static java.math.BigInteger.*;
import static java.util.Arrays.*;
import javax.xml.ws.Holder;

//<editor-fold defaultstate="collapsed" desc="Main">
public class Task{
// https://netbeans.org/kb/73/java/editor-codereference_ru.html#display
    private void run() {
        try {
            Locale.setDefault(Locale.US);
        } catch (Exception e) {
        }
        boolean oj = true;
        try {
            oj = System.getProperty("MYLOCAL") == null;
        } catch (Exception e) {
        }

        if (oj) {
            sc = new FastScanner(new InputStreamReader(System.in));
            out = new PrintWriter(new OutputStreamWriter(System.out));
        } else {
            try {
                sc = new FastScanner(new FileReader("input.txt"));
                out = new PrintWriter(new FileWriter("output.txt"));
            } catch (IOException e) {
                MLE();
            }
        }
        Solver s = new Solver();
        s.sc = sc;
        s.out = out;
        s.solve();
        if (!oj) {
            err.println("Time: " + (System.currentTimeMillis() - timeBegin) / 1e3);
            err.printf("Mem: %d\n", (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) >> 20);
        }
        out.flush();
    }

    private void show(int[] arr) {
        for (int v : arr) {
            err.print(" " + v);
        }
        err.println();
    }

    public static void exit() {
        err.println("Time: " + (System.currentTimeMillis() - timeBegin) / 1e3);
        out.flush();
        out.close();
        System.exit(0);
    }

    public static void MLE() {
        int[][] arr = new int[1024 * 1024][];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = new int[1024 * 1024];
        }
    }

    public static void main(String[] args) {
        new Task().run();
    }

    static long timeBegin = System.currentTimeMillis();
    static FastScanner sc;
    static PrintWriter out;
    static PrintStream err = System.err;
}
//</editor-fold>

//<editor-fold defaultstate="collapsed" desc="FastScanner">
class FastScanner {

    BufferedReader br;
    StringTokenizer st;

    FastScanner(InputStreamReader reader) {
        br = new BufferedReader(reader);
        st = new StringTokenizer("");
    }

    String next() {
        while (!st.hasMoreElements()) {
            try {
                st = new StringTokenizer(br.readLine());
            } catch (IOException ex) {
                Task.MLE();
            }
        }
        return st.nextToken();
    }

    int nextInt() {
        return Integer.parseInt(next());
    }

    long nextLong() {
        return Long.parseLong(next());
    }
    double nextDouble() {
        return Double.parseDouble(next());
    }
}
//</editor-fold>

class Solver {
    void ass(boolean OK) { if(!OK)Task.MLE(); }

    FastScanner sc;
    PrintWriter out;
    static PrintStream err = System.err;

    final int mod = (int)1e9 + 7;
    int[] str;
    long[] val;
    int[] len;
    int q;
    int[] from;
    int[][] to;
    long[] pow10 = new long[(int)1e5 + 100];
    {
        pow10[0] = 1;
        for (int i = 1; i < pow10.length; i++)
            pow10[i] = 10 * pow10[i-1] % mod;
    }

    void solve(){
        {
            String s = sc.next();
            str = new int[s.length()];
            for (int i = 0; i < s.length(); i++)
                str[i] = s.charAt(i) - '0';
        }

        val = new long[10];
        len = new int[10];
        for (int i = 0; i <= 9; i++) {
            val[i] = i;
            len[i] = 1;
        }

        q = sc.nextInt();
        from = new int[q];
        to = new int[q][];
        for (int i = 0; i < q; i++) {
            String s;
            try {
                s = sc.br.readLine();
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException();
            }
            int pos = s.indexOf("->");
            String[] arr = { s.substring(0,pos), s.substring(pos+2) };
            from[i] = Integer.parseInt(arr[0].trim());
            arr[1] = arr[1].trim();
            to[i] = new int[arr[1].length()];
            for (int j = 0; j < arr[1].length(); j++)
                to[i][j] = arr[1].charAt(j) - '0';
        }

        for( int i = q-1; 0 <= i; --i ){
            long newVal = 0;
            int newLen = 0;
            for( int j = to[i].length-1; 0 <= j; --j ){
                int x = to[i][j];
                newVal += val[x] * pow10[newLen] % mod;
                newVal %= mod;
                newLen += len[x];
            }
            val[from[i]] = newVal;
            len[from[i]] = newLen;
        }

        long ans = 0;
        int len = 0;
        for (int i = str.length-1; 0 <= i; --i) {
            int x = str[i];
            ans = (ans + val[x]*pow10[len]) % mod;
            len += this.len[x];
        }
        out.println( ans );
    }

}


import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import java.math.BigInteger;
import static java.math.BigInteger.*;
import static java.util.Arrays.*;
import javax.xml.ws.Holder;

//<editor-fold defaultstate="collapsed" desc="Main">
public class Task{
// https://netbeans.org/kb/73/java/editor-codereference_ru.html#display
    private void run() {
        try {
            Locale.setDefault(Locale.US);
        } catch (Exception e) {
        }
        boolean oj = true;
        try {
            oj = System.getProperty("MYLOCAL") == null;
        } catch (Exception e) {
        }

        if (oj) {
            sc = new FastScanner(new InputStreamReader(System.in));
            out = new PrintWriter(new OutputStreamWriter(System.out));
        } else {
            try {
                sc = new FastScanner(new FileReader("input.txt"));
                out = new PrintWriter(new FileWriter("output.txt"));
            } catch (IOException e) {
                MLE();
            }
        }
        Solver s = new Solver();
        s.sc = sc;
        s.out = out;
        s.solve();
        if (!oj) {
            err.println("Time: " + (System.currentTimeMillis() - timeBegin) / 1e3);
            err.printf("Mem: %d\n", (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) >> 20);
        }
        out.flush();
    }

    private void show(int[] arr) {
        for (int v : arr) {
            err.print(" " + v);
        }
        err.println();
    }

    public static void exit() {
        err.println("Time: " + (System.currentTimeMillis() - timeBegin) / 1e3);
        out.flush();
        out.close();
        System.exit(0);
    }

    public static void MLE() {
        int[][] arr = new int[1024 * 1024][];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = new int[1024 * 1024];
        }
    }

    public static void main(String[] args) {
        new Task().run();
    }

    static long timeBegin = System.currentTimeMillis();
    static FastScanner sc;
    static PrintWriter out;
    static PrintStream err = System.err;
}
//</editor-fold>

//<editor-fold defaultstate="collapsed" desc="FastScanner">
class FastScanner {

    BufferedReader br;
    StringTokenizer st;

    FastScanner(InputStreamReader reader) {
        br = new BufferedReader(reader);
        st = new StringTokenizer("");
    }

    String next() {
        while (!st.hasMoreElements()) {
            try {
                st = new StringTokenizer(br.readLine());
            } catch (IOException ex) {
                Task.MLE();
            }
        }
        return st.nextToken();
    }

    int nextInt() {
        return Integer.parseInt(next());
    }

    long nextLong() {
        return Long.parseLong(next());
    }
    double nextDouble() {
        return Double.parseDouble(next());
    }
}
//</editor-fold>

class Solver {
    void ass(boolean OK) { if(!OK)Task.MLE(); }

    FastScanner sc;
    PrintWriter out;
    static PrintStream err = System.err;

    final int mod = (int)1e9 + 7;
    int[] str;
    long[] val;
    int[] len;
    int q;
    int[] from;
    int[][] to;
    long[] pow10 = new long[(int)1e6 + 100];
    {
        pow10[0] = 1;
        for (int i = 1; i < pow10.length; i++)
            pow10[i] = 10 * pow10[i-1] % mod;
    }

    void solve(){
        {
            String s = sc.next();
            str = new int[s.length()];
            for (int i = 0; i < s.length(); i++)
                str[i] = s.charAt(i) - '0';
        }

        val = new long[10];
        len = new int[10];
        for (int i = 0; i <= 9; i++) {
            val[i] = i;
            len[i] = 1;
        }

        q = sc.nextInt();
        from = new int[q];
        to = new int[q][];
        for (int i = 0; i < q; i++) {
            String s;
            try {
                s = sc.br.readLine();
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException();
            }
            int pos = s.indexOf("->");
            String[] arr = { s.substring(0,pos), s.substring(pos+2) };
            from[i] = Integer.parseInt(arr[0].trim());
            arr[1] = arr[1].trim();
            to[i] = new int[arr[1].length()];
            for (int j = 0; j < arr[1].length(); j++)
                to[i][j] = arr[1].charAt(j) - '0';
        }

        for( int i = q-1; 0 <= i; --i ){
            long newVal = 0;
            int newLen = 0;
            for( int j = to[i].length-1; 0 <= j; --j ){
                int x = to[i][j];
                newVal += val[x] * pow10[newLen] % mod;
                newVal %= mod;
                newLen += len[x];
            }
            val[from[i]] = newVal;
            len[from[i]] = newLen;
        }

        long ans = 0;
        int len = 0;
        for (int i = str.length-1; 0 <= i; --i) {
            int x = str[i];
            ans = (ans + val[x]*pow10[len]) % mod;
            len += this.len[x];
        }
        out.println( ans );
    }

}


import java.util.*;
import java.io.*;
public class C {
    public static PrintStream out = System.out;
    public static InputReader in = new InputReader(System.in);
    static long MOD = (long) 1e9 + 7;
    static class Node {
        static Node EMPTY_LEAF = new Node(0);
        int i;
        List<Node> children = new ArrayList<Node>();
        Node(int i) {
            this.i = i;
        }
        long _ans = -3;
        long _size = -3;
        long ans() {
            if (_ans != -3) return _ans;
            if (children.size() == 0) {
                return i;
            }
            long digits = 0;
            long ret = 0;
            for (int i = children.size() - 1; i >= 0; i--) {
                Node node = children.get(i);
                if (node == EMPTY_LEAF) continue;
                ret = (ret + (node.ans() * modPow(digits)) % MOD) % MOD;
                digits += node.size();
                digits %= MOD - 1;
            }
            _ans = ret;
            return ret;
        }
        long size() {
            if (_size != -3) return _size;
            if (children.size() == 0) {
                return 1;
            }
            int ret = 0;
            for (int i = 0; i < children.size(); i++) {
                ret += children.get(i).size();
                ret %= MOD - 1;
            }
            _size = ret;
            return ret;
        }
    }
    static long modPow(long digits) {
        if (digits == 0) return 1;
        if (digits % 2 == 1) return 10L * modPow(digits - 1) % MOD;
        long c = modPow(digits / 2);
        return c * c % MOD;
    }
    static long[] tenPow = new long[200001];
    public static void main(String args[]) {
        long pow = 1;
        for (int i = 0; i < tenPow.length; i++) {
            tenPow[i] = pow;
            pow = (pow * 10) % MOD;
        }
        String S = in.next();
        int N = in.nextInt();
        nodes = new Node[10];
        Node root = new Node(-1);
        for (int i = 0; i < S.length(); i++) {
            root.children.add(get((int) S.charAt(i) - '0'));
        }
        for (int i = 0; i < N; i++) {
            String Q = in.next();
            int d = (int) Q.charAt(0) - '0';
            if (nodes[d] != null) {
                Node nd = nodes[d];
                nodes[d] = null;
                for (int j = 3; j < Q.length(); j++) {
                    nd.children.add(get((int) Q.charAt(j) - '0'));
                }
                if (Q.length() == 3) {
                    nd.children.add(Node.EMPTY_LEAF);
                }
            }
        }
        out.println(root.ans());
    }
    static Node[] nodes;
    static Node get(int i) {
        if (nodes[i] == null) {
            nodes[i] = new Node(i);
        }
        return nodes[i];
    }
}
class InputReader {
    public BufferedReader reader;
    public StringTokenizer tokenizer;
    public InputReader(InputStream stream) {
	reader = new BufferedReader(new InputStreamReader(stream), 32768);
	tokenizer = null;
    }
    public String next() {
	while (tokenizer == null || !tokenizer.hasMoreTokens()) {
	    try {
		tokenizer = new StringTokenizer(reader.readLine());
	    } catch (IOException e) {
		throw new RuntimeException(e);
	    }
	}
	return tokenizer.nextToken();
    }
    public double nextDouble() {
	return Double.parseDouble(next());
    }
    public long nextLong() {
	return Long.parseLong(next());
    }
    public int nextInt() {
	return Integer.parseInt(next());
    }
}


import java.util.*;
import java.io.*;
public class C {
    public static PrintStream out = System.out;
    public static InputReader in = new InputReader(System.in);
    static long MOD = (long) 1e9 + 7;
    static class Node {
        int i;
        List<Node> children = new ArrayList<Node>();
        Node(int i) {
            this.i = i;
        }
        long ans() {
            if (children.size() == 0) {
                if (i == -2) return 0;
                return i;
            }
            int digits = 0;
            long ret = 0;
            for (int i = children.size() - 1; i >= 0; i--) {
                Node node = children.get(i);
                ret = (ret + node.ans() * modPow(10, digits)) % MOD;
                digits += node.size();
            }
            return ret;
        }
        int size() {
            if (children.size() == 0) {
                if (i == -2) return 0;
                return 1;
            }
            int ret = 0;
            for (int i = 0; i < children.size(); i++) {
                ret += children.get(i).size();
            }
            return ret;
        }
    }
    static long modPow(long a, long b) {
        if (b == 0) return 1;
        long r = 1;
        if (b % 2 == 1) {
            r *= a;
            b--;
        }
        long c = modPow(a, b / 2);
        r = r * c * c % MOD;
        return r;
    }
    public static void main(String args[]) {
        String S = in.next();
        int N = in.nextInt();
        nodes = new Node[10];
        Node root = new Node(-1);
        for (int i = 0; i < S.length(); i++) {
            root.children.add(get((int) S.charAt(i) - '0'));
        }
        for (int i = 0; i < N; i++) {
            String Q = in.next();
            int d = (int) Q.charAt(0) - '0';
            if (nodes[d] != null) {
                Node nd = nodes[d];
                nodes[d] = null;
                for (int j = 3; j < Q.length(); j++) {
                    nd.children.add(get((int) Q.charAt(j) - '0'));
                }
                if (Q.length() == 3) {
                    nd.children.add(new Node(-2));
                }
            }
        }
        out.println(root.ans());
    }
    static Node[] nodes;
    static Node get(int i) {
        if (nodes[i] == null) {
            nodes[i] = new Node(i);
        }
        return nodes[i];
    }
}
class InputReader {
    public BufferedReader reader;
    public StringTokenizer tokenizer;
    public InputReader(InputStream stream) {
	reader = new BufferedReader(new InputStreamReader(stream), 32768);
	tokenizer = null;
    }
    public String next() {
	while (tokenizer == null || !tokenizer.hasMoreTokens()) {
	    try {
		tokenizer = new StringTokenizer(reader.readLine());
	    } catch (IOException e) {
		throw new RuntimeException(e);
	    }
	}
	return tokenizer.nextToken();
    }
    public double nextDouble() {
	return Double.parseDouble(next());
    }
    public long nextLong() {
	return Long.parseLong(next());
    }
    public int nextInt() {
	return Integer.parseInt(next());
    }
}


import java.util.*;
import java.io.*;
public class C {
    public static PrintStream out = System.out;
    public static InputReader in = new InputReader(System.in);
    static long MOD = (long) 1e9 + 7;
    static class Node {
        static Node EMPTY_LEAF = new Node(0);
        int i;
        List<Node> children = new ArrayList<Node>();
        Node(int i) {
            this.i = i;
        }
        long _ans = -3;
        long _size = -3;
        long ans() {
            if (_ans != -3) return _ans;
            if (children.size() == 0) {
                if (this == EMPTY_LEAF) return 0;
                return i;
            }
            long digits = 0;
            long ret = 0;
            for (int i = children.size() - 1; i >= 0; i--) {
                Node node = children.get(i);
                ret = (ret + (node.ans() * modPow(digits)) % MOD) % MOD;
                digits += node.size();
                digits %= MOD - 1;
            }
            _ans = ret;
            return ret;
        }
        long size() {
            if (_size != -3) return _size;
            if (children.size() == 0) {
                if (this == EMPTY_LEAF) return 0;
                return 1;
            }
            int ret = 0;
            for (int i = 0; i < children.size(); i++) {
                ret += children.get(i).size();
                ret %= MOD - 1;
            }
            _size = ret;
            return ret;
        }
    }
    static long modPow(long digits) {
        if (digits == 0) return 1;
        if (digits % 2 == 1) return 10L * modPow(digits - 1) % MOD;
        long c = modPow(digits / 2);
        return c * c % MOD;
    }
    static long[] tenPow = new long[200001];
    public static void main(String args[]) {
        long pow = 1;
        for (int i = 0; i < tenPow.length; i++) {
            tenPow[i] = pow;
            pow = (pow * 10) % MOD;
        }
        String S = in.next();
        int N = in.nextInt();
        nodes = new Node[10];
        Node root = new Node(-1);
        for (int i = 0; i < S.length(); i++) {
            root.children.add(get((int) S.charAt(i) - '0'));
        }
        for (int i = 0; i < N; i++) {
            String Q = in.next();
            int d = (int) Q.charAt(0) - '0';
            if (nodes[d] != null) {
                Node nd = nodes[d];
                nodes[d] = null;
                for (int j = 3; j < Q.length(); j++) {
                    nd.children.add(get((int) Q.charAt(j) - '0'));
                }
                if (Q.length() == 3) {
                    nd.children.add(Node.EMPTY_LEAF);
                }
            }
        }
        out.println(root.ans());
    }
    static Node[] nodes;
    static Node get(int i) {
        if (nodes[i] == null) {
            nodes[i] = new Node(i);
        }
        return nodes[i];
    }
}
class InputReader {
    public BufferedReader reader;
    public StringTokenizer tokenizer;
    public InputReader(InputStream stream) {
	reader = new BufferedReader(new InputStreamReader(stream), 32768);
	tokenizer = null;
    }
    public String next() {
	while (tokenizer == null || !tokenizer.hasMoreTokens()) {
	    try {
		tokenizer = new StringTokenizer(reader.readLine());
	    } catch (IOException e) {
		throw new RuntimeException(e);
	    }
	}
	return tokenizer.nextToken();
    }
    public double nextDouble() {
	return Double.parseDouble(next());
    }
    public long nextLong() {
	return Long.parseLong(next());
    }
    public int nextInt() {
	return Integer.parseInt(next());
    }
}


import java.util.*;
import java.io.*;
public class C {
    public static PrintStream out = System.out;
    public static InputReader in = new InputReader(System.in);
    static long MOD = (long) 1e9 + 7;
    static class Node {
        int i;
        List<Node> children = new ArrayList<Node>();
        Node(int i) {
            this.i = i;
        }
        long _ans = -3;
        int _size = -3;
        long ans() {
            if (_ans != -3) return _ans;
            if (children.size() == 0) {
                if (i == -2) return 0;
                return i;
            }
            int digits = 0;
            long ret = 0;
            for (int i = children.size() - 1; i >= 0; i--) {
                Node node = children.get(i);
                ret = (ret + node.ans() * modPow(digits)) % MOD;
                digits += node.size();
            }
            _ans = ret;
            return ret;
        }
        int size() {
            if (_size != -3) return _size;
            if (children.size() == 0) {
                if (i == -2) return 0;
                return 1;
            }
            int ret = 0;
            for (int i = 0; i < children.size(); i++) {
                ret += children.get(i).size();
            }
            _size = ret;
            return ret;
        }
    }
    static long modPow(int digits) {
        if (digits == 0) return 1;
        if (digits % 2 == 1) return 10L * modPow(digits - 1) % MOD;
        long c = modPow(digits / 2);
        return c * c % MOD;
    }
    static long[] tenPow = new long[200001];
    public static void main(String args[]) {
        long pow = 1;
        for (int i = 0; i < tenPow.length; i++) {
            tenPow[i] = pow;
            pow = (pow * 10) % MOD;
        }
        String S = in.next();
        int N = in.nextInt();
        nodes = new Node[10];
        Node root = new Node(-1);
        for (int i = 0; i < S.length(); i++) {
            root.children.add(get((int) S.charAt(i) - '0'));
        }
        for (int i = 0; i < N; i++) {
            String Q = in.next();
            int d = (int) Q.charAt(0) - '0';
            if (nodes[d] != null) {
                Node nd = nodes[d];
                nodes[d] = null;
                for (int j = 3; j < Q.length(); j++) {
                    nd.children.add(get((int) Q.charAt(j) - '0'));
                }
                if (Q.length() == 3) {
                    nd.children.add(new Node(-2));
                }
            }
        }
        out.println(root.ans());
    }
    static Node[] nodes;
    static Node get(int i) {
        if (nodes[i] == null) {
            nodes[i] = new Node(i);
        }
        return nodes[i];
    }
}
class InputReader {
    public BufferedReader reader;
    public StringTokenizer tokenizer;
    public InputReader(InputStream stream) {
	reader = new BufferedReader(new InputStreamReader(stream), 32768);
	tokenizer = null;
    }
    public String next() {
	while (tokenizer == null || !tokenizer.hasMoreTokens()) {
	    try {
		tokenizer = new StringTokenizer(reader.readLine());
	    } catch (IOException e) {
		throw new RuntimeException(e);
	    }
	}
	return tokenizer.nextToken();
    }
    public double nextDouble() {
	return Double.parseDouble(next());
    }
    public long nextLong() {
	return Long.parseLong(next());
    }
    public int nextInt() {
	return Integer.parseInt(next());
    }
}


import java.util.*;
import java.io.*;
public class C {
    public static PrintStream out = System.out;
    public static InputReader in = new InputReader(System.in);
    static long MOD = (long) 1e9 + 7;
    static class Node {
        int i;
        List<Node> children = new ArrayList<Node>();
        Node(int i) {
            this.i = i;
        }
        long ans() {
            if (children.size() == 0) {
                if (i == -2) return 0;
                return i;
            }
            int digits = 0;
            long ret = 0;
            for (int i = children.size() - 1; i >= 0; i--) {
                Node node = children.get(i);
                ret = (ret + node.ans() * tenPow[digits]) % MOD;
                digits += node.size();
            }
            return ret;
        }
        int size() {
            if (children.size() == 0) {
                if (i == -2) return 0;
                return 1;
            }
            int ret = 0;
            for (int i = 0; i < children.size(); i++) {
                ret += children.get(i).size();
            }
            return ret;
        }
    }
    static long[] tenPow = new long[1000001];
    public static void main(String args[]) {
        long pow = 1;
        for (int i = 0; i < tenPow.length; i++) {
            tenPow[i] = pow;
            pow = (pow * 10) % MOD;
        }
        String S = in.next();
        int N = in.nextInt();
        nodes = new Node[10];
        Node root = new Node(-1);
        for (int i = 0; i < S.length(); i++) {
            root.children.add(get((int) S.charAt(i) - '0'));
        }
        for (int i = 0; i < N; i++) {
            String Q = in.next();
            int d = (int) Q.charAt(0) - '0';
            if (nodes[d] != null) {
                Node nd = nodes[d];
                nodes[d] = null;
                for (int j = 3; j < Q.length(); j++) {
                    nd.children.add(get((int) Q.charAt(j) - '0'));
                }
                if (Q.length() == 3) {
                    nd.children.add(new Node(-2));
                }
            }
        }
        out.println(root.ans());
    }
    static Node[] nodes;
    static Node get(int i) {
        if (nodes[i] == null) {
            nodes[i] = new Node(i);
        }
        return nodes[i];
    }
}
class InputReader {
    public BufferedReader reader;
    public StringTokenizer tokenizer;
    public InputReader(InputStream stream) {
	reader = new BufferedReader(new InputStreamReader(stream), 32768);
	tokenizer = null;
    }
    public String next() {
	while (tokenizer == null || !tokenizer.hasMoreTokens()) {
	    try {
		tokenizer = new StringTokenizer(reader.readLine());
	    } catch (IOException e) {
		throw new RuntimeException(e);
	    }
	}
	return tokenizer.nextToken();
    }
    public double nextDouble() {
	return Double.parseDouble(next());
    }
    public long nextLong() {
	return Long.parseLong(next());
    }
    public int nextInt() {
	return Integer.parseInt(next());
    }
}


#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <string>
using namespace std;
typedef long long ll;
string tA, tB;
bool cmp(const string &A,const string &B) {
    tA = A + B;
    tB = B + A;
    int len = tA.size();
    for(int i = 0; i < len; i++) {
        if(tA[i] > tB[i]) return false;
        else if (tA[i] < tB[i]) return true;
    }
    return true;
}

const int maxn = 50000 + 7;
string strs[maxn];

int main() {
    int n;
    cin >> n;
    for(int i = 0; i < n; i++) {
         cin >> strs[i];
    }
    sort(strs, strs + n, cmp);
    for(int i = 0; i < n; i++) {
         cout << strs[i];
    }
    return 0;
}


#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <string>
using namespace std;
typedef long long ll;

bool cmp(const string &A,const string &B) {
    int lena = A.length(), lenb = B.length();
    for(int i = 0; i < max(lena, lenb); i++) {
        if(A[i % lena] == B[i % lenb]) {
            continue;
        } else if(A[i % lena] > B[i % lenb]) {
             return false;
        } else {
            return true;
        }
    }
    return true;
}

const int maxn = 50000 + 7;
string strs[maxn];

int main() {
    int n;
    cin >> n;
    for(int i = 0; i < n; i++) {
         cin >> strs[i];
    }
    sort(strs, strs + n, cmp);
    for(int i = 0; i < n; i++) {
         cout << strs[i];
    }
    return 0;
}


#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <string>
using namespace std;
typedef long long ll;
string tA, tB;
bool cmp(const string A,const string B) {
    tA = A + B;
    tB = B + A;
    int len = tA.size();
    for(int i = 0; i < len; i++) {
        if(tA[i] > tB[i]) return false;
        else if (tA[i] < tB[i]) return true;
    }
    return true;
}

const int maxn = 50000 + 7;
string strs[maxn];

int main() {
    int n;
    cin >> n;
    for(int i = 0; i < n; i++) {
         cin >> strs[i];
    }
    sort(strs, strs + n, cmp);
    for(int i = 0; i < n; i++) {
         cout << strs[i];
    }
    return 0;
}


#include<bits/stdc++.h>

using namespace std;

#define in(a,x,y) (a>=x && a<=y)
#define out(a,x,y) (!in(a,x,y))
#define sz(a) ((int)a.size())
#define repv(i,a) for(int i=0;i<sz(a);i++)
#define revv(i,a) for(int i=sz(a)-1;i>=0;i--)
#define rep(i,a,b) for(int i=a;i<=b;i++)
#define rev(i,a,b) for(int i=a;i>=b;i--)
#define all(a) a.begin(),a.end()
#define pb push_back

#define AND(a,b) ((a) & (b))
#define OR(a,b) ((a)|(b))
#define XOR(a,b) ((a) ^ (b))
#define xx first
#define yy second
#define mp make_pair
#define sqr(x) ((x)*(x))
#define sqrt(x) sqrt(1.0*(x))

#define LB(a,x) (lower_bound(all(a),x)-a.begin()) //  first element in the range [first,last) which does not compare less than val.
#define UB(a,x) (upper_bound(all(a),x)-a.begin()) //  first element in the range [first,last) which compares greater than val.
#define forit(it, s) for(__typeof(s.begin()) it = s.begin(); it != s.end(); it++)
#define left nokol_left
#define right nokol_right
#define countbit(x) __builtin_popcountll((ll)x)
#define PQ priority_queue
#define FAST ios_base::sync_with_stdio(0);cin.tie(0);
#define Unique(store) store.resize(unique(store.begin(),store.end())-store.begin())
#define READ(f) freopen(f, "r", stdin)
#define WRITE(f) freopen(f, "w", stdout)

typedef long long ll;
typedef unsigned int uint;
typedef unsigned long long ull;
typedef pair<int,int> pii;
typedef pair<long long,long long> pll;
typedef vector<int> vi;
typedef vector<long long> vll;

template<class T>T __sqr(const T x){return x*x;}
template< class T, class X > inline T __pow(T a,X y) {T z=1; rep(i,1,y){z*=a;} return z; }
template< class T > inline T gcd(T a,T b) {a=abs(a);b=abs(b); if(!b) return a; return __gcd(b,a%b);}
template< class T > inline T lcm(T a,T b) {a=abs(a);b=abs(b); return (a/__gcd(a,b))*b;}
inline bool ispow2(int x){return (x!=0 && (x&(x-1))==0);}
template<class T>void UpdateMin(T &x,T y){  if(y<x){x=y;}}
template<class T>void UpdateMax(T &x,T y){if(x<y){x=y;}}
template<class T,class X, class Y > inline T bigmod(T n,X m,Y mod){ull ret=1, a = n%mod ; while(m){ if(m&1)ret=(ret*a)%mod; m>>=1; a=(a*a)%mod; }ret%=mod;return (T)ret;}
template<class T, class Y > inline T modinv(T n,Y mod) {return bigmod(n,mod-2,mod);}

template<class T,class X> int getbit(T s,X i) { return (s >> i) & 1; }
template<class T,class X> T onbit(T s, X i) { return s | (T(1) << i); }
template<class T,class X> T offbit(T s, X i) { return s & (~(T(1) << i)); }
template<class T> inline void read(T &n){char c;for (c = getchar(); !(c >= '0' && c <= '9'); c = getchar()); n = c - '0';for (c = getchar(); c >= '0' && c <= '9'; c = getchar()) n = n * 10 + c - '0';}

void extended_euclid(ll a,ll b,ll &x,ll &y){ if(!b){ x = 1 , y = 0  ;  return ;} ll xx,yy; extended_euclid(b,a%b,xx,yy); x = yy; y = xx - (a/b)*yy; }
pair<ll, pair<ll, ll> > extendedEuclid(ll a, ll b) { ll x = 1, y = 0; ll xLast = 0, yLast = 1; ll q, r, m, n; while(a != 0) {q = b / a; r = b % a; m = xLast - q * x; n = yLast - q * y; xLast = x, yLast = y; x = m, y = n; b = a, a = r; } return make_pair(b, make_pair(xLast, yLast)); }

const ll mod[]  ={0,1000000007,1000000009,1000000021,1000000033,1000000097,1000000093,1000000097,1000000103};
const ll base[] ={0,1000003,1000033,1000037,1000039,1000081,1000099,1000117,1000121};

#define pi acos(-1.0)
#define eps  1e-12
#define MX   (lmt+20)
#define inf  1000000000000000000LL
#define MOD  1000000007LL
//---------->0123456789123465789
#define lmt  50000

struct DT{
    string a ;
    int len;
    bool operator<(const DT &b) const {

        return (a + b.a) <= (b.a + a);
    }
}d[MX];

int main()
{

    int n;
    scanf("%d",&n);
    rep(i,1,n){
        cin>>d[i].a;
//        int len = d[i].len = d[i].a.size();
//        rep(j,len,50-1) d[i].a += (char)d[i].a[j%len];
    }

    sort(d+1,d+1+n);

    rep(i,1,n) cout<<d[i].a;
    puts("");

//    string ans= "abaabaabaacaabaacacacaaaabbacbaacbbbbcabcabbcccaabcc";
//    cout<<ans<<endl;

    return 0;
}
/*
2
baa
baab

2
aab
aaba
*/