#include <bits/stdc++.h>
using namespace std;
const int MAXN = 400000;
const int MOD = 777777777;
struct NODE {
  int left, right;
  int s, t;
  long long a[3][3];
} f[MAXN];
int h[3][3];
void ai00(long long a[][3], int b) {
  memset(a, 0, sizeof(long long) * 9);
  if (b == 0) {
    a[0][0] = a[1][1] = a[2][2] = 1;
  } else {
    a[b - 1][b - 1] = 1;
  }
}
void ai00(long long a[][3], long long b[][3], long long c[][3]) {
  memset(a, 0, sizeof(long long) * 9);
  for (int i = 0; i < 3; ++i)
    for (int j = 0; j < 3; ++j)
      for (int q = 0; q < 3; ++q)
        for (int p = 0; p < 3; ++p)
          a[i][j] = (a[i][j] + b[i][q] * c[p][j] * h[q][p]) % MOD;
}
void ai00(int n) {
  int m = 0;
  f[m].s = 1;
  f[m++].t = n;
  for (int i = 0; i < m; ++i) {
    if (f[i].s != f[i].t) {
      int mid = (f[i].s + f[i].t) >> 1;
      f[i].left = m;
      f[m].s = f[i].s;
      f[m++].t = mid;
      f[i].right = m;
      f[m].s = mid + 1;
      f[m++].t = f[i].t;
    }
  }
  for (int i = m - 1; i >= 0; --i)
    if (f[i].s == f[i].t)
      ai00(f[i].a, 0);
    else
      ai00(f[i].a, f[f[i].left].a, f[f[i].right].a);
}
void ai00(NODE &a, int x, int y) {
  if (a.s == a.t) {
    ai00(a.a, y);
    return;
  }
  if (f[a.left].t >= x)
    ai00(f[a.left], x, y);
  else
    ai00(f[a.right], x, y);
  ai00(a.a, f[a.left].a, f[a.right].a);
}
int ai00() {
  long long ans = 0;
  for (int i = 0; i < 3; ++i)
    for (int j = 0; j < 3; ++j) ans = (ans + f[0].a[i][j]) % MOD;
  return ans;
}
int main() {
  int n, m;
  while (scanf("%d %d", &n, &m) != EOF) {
    for (int i = 0; i < 3; ++i)
      for (int j = 0; j < 3; ++j) scanf("%d", &h[i][j]);
    ai00(n);
    for (int i = 0; i < m; ++i) {
      int x, y;
      scanf("%d %d", &x, &y);
      ai00(f[0], x, y);
      printf("%d\n", ai00());
    }
  }
}
