/* -*- coding: utf-8 -*- * * 307.cc: No.307 最近色塗る問題多くない? - yukicoder */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; /* constant */ const int MAX_H = 200; const int MAX_W = 200; const int MAX_N = MAX_H * MAX_W; const int dxs[] = {1, 0, -1, 0}, dys[] = {0, -1, 0, 1}; /* typedef */ typedef queue qi; struct UFT { int links[MAX_N], ranks[MAX_N], sizes[MAX_N]; void clear(int n) { for (int i = 0; i < n; i++) links[i] = i, ranks[i] = sizes[i] = 1; } UFT() {} UFT(int n) { clear(n); } int root(int i) { int i0 = i; while (links[i0] != i0) i0 = links[i0]; return (links[i] = i0); } int rank(int i) { return ranks[root(i)]; } int size(int i) { return sizes[root(i)]; } bool same(int i, int j) { return root(i) == root(j); } int merge(int i0, int i1) { int r0 = root(i0), r1 = root(i1), mr; if (r0 == r1) return r0; if (ranks[r0] == ranks[r1]) { links[r1] = r0; sizes[r0] += sizes[r1]; ranks[r0]++; mr = r0; } else if (ranks[r0] > ranks[r1]) { links[r1] = r0; sizes[r0] += sizes[r1]; mr = r0; } else { links[r0] = r1; sizes[r1] += sizes[r0]; mr = r1; } return mr; } }; /* global variables */ int h, w, n; bool as[MAX_N], used[MAX_N]; UFT uft; /* subroutines */ void printflds(bool bs[]) { for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { if (x) putchar(' '); printf("%d", bs[uft.root(y * w + x)]); } putchar('\n'); } } /* main */ int main() { cin >> h >> w; n = h * w; for (int i = 0; i < n; i++) cin >> as[i]; //printflds(as); uft.clear(n); for (int y = 0, pos = 0; y < h; y++) for (int x = 0; x < w; x++, pos++) if (! used[pos]) { bool c = as[pos]; qi q; q.push(pos); while (! q.empty()) { int u = q.front(); q.pop(); int ux = u % w, uy = u / w; for (int di = 0; di < 4; di++) { int vx = ux + dxs[di], vy = uy + dys[di]; if (vx >= 0 && vx < w && vy >= 0 && vy < h) { int v = vy * w + vx; if (! used[v] && as[v] == c) { used[v] = true; q.push(v); if (! uft.same(u, v)) uft.merge(u, v); } } } } } for (int y = 0; false && y < h; y++) { for (int x = 0; x < w; x++) printf("%2d ", uft.root(y * w + x)); putchar('\n'); } int q; cin >> q; while (q--) { int yi, xi; bool ci; cin >> yi >> xi >> ci; yi--, xi--; int p = yi * w + xi, rp = uft.root(p); if (as[rp] == ci) continue; if (uft.size(rp) == n) { as[rp] = ci; continue; } memset(used, false, sizeof(used)); used[p] = true; qi q; q.push(p); while (! q.empty()) { int u = q.front(); q.pop(); int ux = u % w, uy = u / w; for (int di = 0; di < 4; di++) { int vx = ux + dxs[di], vy = uy + dys[di]; if (vx >= 0 && vx < w && vy >= 0 && vy < h) { int v = vy * w + vx; if (! used[v] && as[uft.root(v)] != ci) { used[v] = true; q.push(v); if (! uft.same(u, v)) uft.merge(u, v); } } } } as[uft.root(p)] = ci; } printflds(as); return 0; }