結果
| 問題 |
No.307 最近色塗る問題多くない?
|
| コンテスト | |
| ユーザー |
|
| 提出日時 | 2021-04-25 16:25:50 |
| 言語 | C++17 (gcc 13.3.0 + boost 1.87.0) |
| 結果 |
AC
|
| 実行時間 | 1,581 ms / 4,000 ms |
| コード長 | 2,752 bytes |
| コンパイル時間 | 4,449 ms |
| コンパイル使用メモリ | 207,552 KB |
| 最終ジャッジ日時 | 2025-01-21 00:57:09 |
|
ジャッジサーバーID (参考情報) |
judge1 / judge1 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| other | AC * 36 |
ソースコード
#include <bits/stdc++.h>
using namespace std;
class union_find {
int n;
int cnt; // number of connected components
vector<int> par;
vector<int> rank;
vector<int> sz; // size of each component
public:
union_find(int n) : n(n), cnt(n), par(n), rank(n), sz(n) {
for (int i = 0; i < n; i++) {
par[i] = i;
sz[i] = 1;
}
}
int find(int x) {
return par[x] == x ? x : par[x] = find(par[x]);
}
void unite(int x, int y) {
x = find(x);
y = find(y);
if (x == y) return;
--cnt;
if (rank[x] < rank[y]) {
par[x] = y;
sz[y] += sz[x];
} else {
par[y] = x;
sz[x] += sz[y];
if (rank[x] == rank[y])
++rank[x];
}
}
bool same(int x, int y) {
return find(x) == find(y);
}
int compCnt() {
return cnt;
}
int size(int x) {
return sz[find(x)];
}
};
int dy[] = {0, 1, 0, -1};
int dx[] = {1, 0, -1, 0};
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int r, c;
cin >> r >> c;
vector<vector<int> > bd(r, vector<int>(c));
for (int i = 0; i < r; i++)
for (int j = 0; j < c; j++)
cin >> bd[i][j];
union_find tree(r * c);
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
for (int k = 0; k < 4; k++) {
int it = i + dy[k];
int jt = j + dx[k];
if (0 <= it && it < r && 0 <= jt && jt < c) {
if (bd[i][j] == bd[it][jt]) {
tree.unite(i * c + j, it * c + jt);
}
}
}
}
}
int q;
cin >> q;
vector<int> xs(q), ys(q), zs(q);
for (int t = 0; t < q; t++)
cin >> ys[t] >> xs[t] >> zs[t];
for (int t = 0; t < q; t++) {
int y = ys[t] - 1;
int x = xs[t] - 1;
int z = zs[t];
int root = tree.find(y * c + x);
if (bd[root/c][root%c] == z)
continue;
set<int> added;
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
if (!tree.same(root, i * c + j)) continue;
for (int k = 0; k < 4; k++) {
int it = i + dy[k];
int jt = j + dx[k];
if (0 <= it && it < r && 0 <= jt && jt < c) {
if (!tree.same(root, it * c + jt)) {
added.insert(it * c + jt);
}
}
}
}
}
for (int a: added)
tree.unite(root, a);
root = tree.find(root);
bd[root/c][root%c] = z;
if (tree.compCnt() == 1)
break;
}
if (tree.compCnt() == 1) {
int root = tree.find(0);
bd[root/c][root%c] = zs.back();
}
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
int root = tree.find(i * c + j);
cout << bd[root/c][root%c] << " ";
}
cout << endl;
}
return 0;
}