#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; #define REP(i,a,b) for(int i=a;i<(int)b;i++) #define rep(i,n) REP(i,0,n) struct UnionFind { vector rank; vector rid; UnionFind(int n) { rank.resize(n); rid.assign(n, -1); } void unite(int u, int v) { u = root(u), v = root(v); if(u == v) { return ; } if(rank[u] < rank[v]) { rid[u] = v; } else { rid[v] = u; if(rank[u] == rank[v]) { rank[u]++; } } } bool same(int u, int v) { return root(u) == root(v); } int root(int x) { if(rid[x] < 0) return x; else return rid[x] = root(rid[x]); } }; int dx[4] = {-1,0,1,0}; int dy[4] = {0,-1,0,1}; int H, W; int A[201][201]; int Q; bool rootCol[200*200+1]; set outers[200*200+1]; // []はroot bool inrange(int y, int x) { return 0<=y&&y> H >> W; rep(i, H) rep(j, W) { cin >> A[i][j]; rootCol[chpos(i, j)] = A[i][j]; } UnionFind uf(H * W + 1); rep(i, H) rep(j, W) { rep(k, 4) { int ni = i+dy[k], nj = j+dx[k]; if(!inrange(ni, nj)) { continue; } if(A[i][j] == A[ni][nj]) { uf.unite(chpos(i, j), chpos(ni, nj)); rootCol[uf.root(chpos(i, j))] = A[i][j]; } else { outers[uf.root(chpos(i, j))].insert(chpos(ni, nj)); } } } DEBUG cin >> Q; rep(_, Q) { int r, c, x; cin >> r >> c >> x; r--, c--; const int RawPos = uf.root(chpos(r, c)); /* cout << "rc outers" << r << ", " << c << endl; for(auto& e: outers[RawPos]) { cout << e << " "; }cout << endl; */ DEBUG auto& refCol = rootCol[RawPos]; if(refCol != x) { refCol = x; vector mv; for(auto& e: outers[RawPos]) { if(rootCol[e] == rootCol[RawPos]) { uf.unite(e, RawPos); mv.push_back(e); } } DEBUG mv.push_back(RawPos); int rt = uf.root(RawPos); rep(i, mv.size()) { if(mv[i] == rt) { continue; } if (outers[rt].size() < outers[mv[i]].size()) { swap(outers[rt], outers[mv[i]]); } outers[rt].insert(outers[mv[i]].begin(), outers[mv[i]].end()); outers[mv[i]].clear(); } } } rep(i, H) { rep(j, W) { if(j) cout << " "; cout << rootCol[uf.root(chpos(i, j))]; } cout << endl; } return 0; }