#include #define GET_MACRO(a, b, c, NAME, ...) NAME #define rep(...) GET_MACRO(__VA_ARGS__, rep3, rep2)(__VA_ARGS__) #define rep2(i, a) rep3 (i, 0, a) #define rep3(i, a, b) for (int i = (a); i < (b); i++) #define repr(...) GET_MACRO(__VA_ARGS__, repr3, repr2)(__VA_ARGS__) #define repr2(i, a) repr3 (i, 0, a) #define repr3(i, a, b) for (int i = (b) - 1; i >= (a); i--) #define chmin(a, b) ((b) < a && (a = (b), true)) #define chmax(a, b) (a < (b) && (a = (b), true)) using namespace std; typedef long long ll; struct UF { vector parent, color; vector> g; UF(int n) : parent(n), color(n), g(n) { rep (i, n) parent[i] = i; } int root(int x) { if (x == parent[x]) return x; else return parent[x] = root(parent[x]); } void merge(int x, int y) { x = root(x); y = root(y); if (x == y) return; if (g[x].size() < g[y].size()) swap(x, y); parent[y] = x; g[x].insert(g[y].begin(), g[y].end()); g[y].clear(); auto it = g[x].begin(); while (it != g[x].end()) { if (root(*it) == x) { g[x].erase(it++); } else ++it; } } bool same(int x, int y) { return root(x) == root(y); } void add(int u, int v) { u = root(u); v = root(v); if (u == v) return; g[u].insert(v); g[v].insert(u); } void update(int x, int c) { x = root(x); if (color[x] == c) return; color[x] = c; vector a(g[x].begin(), g[x].end()); for (int y : a) if (getcolor(y) == c) { merge(x, y); } } int getcolor(int x) { x = root(x); return color[x]; } void collect() { rep (i, parent.size()) { { auto it = g[i].begin(); while (it != g[i].end()) { if (root(*it) != *it) { g[i].insert(root(*it)); } it++; } } { auto it = g[i].begin(); while (it != g[i].end()) { if (root(*it) != *it) { g[i].erase(it++); } else ++it; } } } } }; int g[200][200]; int A[200][200]; int main() { int h, w; cin >> h >> w; UF uf(h * w); rep (i, h) rep (j, w) cin >> A[i][j]; rep (i, h) rep (j, w) uf.color[i * w + j] = A[i][j]; rep (i, h) rep (j, w) { int dy[] = {1, 0}; int dx[] = {0, 1}; rep (k, 2) { int ny = i + dy[k]; int nx = j + dx[k]; if (ny < h && nx < w) { if (A[ny][nx] == A[i][j]) { uf.merge(ny * w + nx, i * w + j); } else { uf.add(ny * w + nx, i * w + j); } } } } int q; cin >> q; rep (i, q) { int r, c, x; scanf("%d %d %d", &r, &c, &x); r--; c--; uf.update(r * w + c, x); if (i % 300 == 0) uf.collect(); } rep (i, h) { rep (j, w) { if (j) cout << " "; cout << uf.getcolor(i * w + j); } cout << endl; } return 0; }