#include <bits/stdc++.h>
using namespace std;
const int mod = 12345, maxn = 1001;
int a[27], v[27], p[maxn], num[maxn], mat[123][123];
char str[15];
int s = 1, one[123][123], tmp[123][123];
void mi(long long a) {
  int i, j, k;
  if (!a)
    for (i = 0; i < s; i++) mat[i][i] = 1;
  else {
    mi(a >> 1);
    memset(tmp, 0, sizeof(tmp));
    for (i = 0; i < s; i++)
      for (j = 0; j < s; j++)
        for (k = 0; k < s; k++)
          tmp[i][j] = (mat[i][k] * mat[k][j] + tmp[i][j]) % mod;
    for (i = 0; i < s; i++)
      for (j = 0; j < s; j++) mat[i][j] = tmp[i][j];
    if (a & 1) {
      memset(tmp, 0, sizeof(tmp));
      for (i = 0; i < s; i++)
        for (j = 0; j < s; j++)
          for (k = 0; k < s; k++)
            tmp[i][j] = (mat[i][k] * one[k][j] + tmp[i][j]) % mod;
      for (i = 0; i < s; i++)
        for (j = 0; j < s; j++) mat[i][j] = tmp[i][j];
    }
  }
}
int main() {
  long long n;
  int i, j, k, c, t, ans = 0;
  scanf("%I64d%d", &n, &c);
  if (c) getchar();
  for (i = 1; i <= c; i++) {
    gets(str + 1);
    p[i] = str[1] - 'A' + 1;
    v[str[1] - 'A' + 1] = 1;
    for (j = 3; str[j] >= '0' && str[j] <= '9'; j++)
      num[i] = num[i] * 10 + str[j] - '0';
    s *= num[i];
  }
  for (i = 1; i <= c; i++) v[p[i]] *= num[i];
  for (i = 0; i < s; i++) {
    t = i;
    for (j = 1; j <= 26; j++)
      if (v[j]) {
        a[j] = t % v[j];
        t /= v[j];
      }
    t = 1;
    for (j = 1; j <= 26; j++)
      if (v[j]) {
        if (a[j] == v[j] - 1)
          one[i][i - a[j] * t]++;
        else
          one[i][i + t]++;
        t *= v[j];
      }
  }
  mi(n);
  for (i = 0; i < s; i++) {
    t = i;
    for (j = 1; j <= 26; j++)
      if (v[j]) {
        a[j] = t % v[j];
        t /= v[j];
        for (k = 1; k <= c && (p[k] != j || a[j] % num[k]); k++)
          ;
        if (k > c) break;
      }
    if (j > 26) ans = (ans + mat[0][i]) % mod;
  }
  printf("%d\n", ans);
  return 0;
}
