This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
//author: Ahmet Alp Orakci
#include <bits/stdc++.h>
using namespace std;
using i64 = long long;
char matrix[1005][1005];
int vis[1005 * 1005];
set <int> adj[1005 * 1005];
int comp[1005 * 1005];
int dx[4] = {0, 1, 0, -1};
int dy[4] = {-1, 0, 1, 0};
struct DSU {
int n;
vector <int> par;
DSU(int n) : n(n) {
par.resize(n);
iota(par.begin(), par.end(), 0);
}
inline int get(int x) {
return par[x] = (x == par[x] ? x : get(par[x]));
}
bool same(int a, int b) {
return get(a) == get(b);
}
bool unite(int u, int v) {
if(same(u, v))
return false;
u = get(u), v = get(v);
par[v] = u;
return true;
}
};
#define ONLINE_JUDGE
void solve() {
memset(vis, -1, sizeof(vis));
int r, c;
cin >> r >> c;
int cnt = 0;
for(int i = 1; i <= r; i++) {
for(int j = 1; j <= c; j++) {
cin >> matrix[i][j];
}
}
DSU dsu((r + 1) * (c +1) + 100);
for(int i = 1; i <= r; i++) {
for(int j = 1; j <= c; j++) {
if(i +1 <= r && matrix[i][j] == matrix[i +1][j]) {
dsu.unite(i * c + j, (i +1) * c + j);
}
if(j +1 <= c && matrix[i][j] == matrix[i][j +1]) {
dsu.unite(i * c + j, i * c + j +1);
}
}
}
vector <int> vec;
for(int i = 1; i <= r; i++) {
for(int j = 1; j <= c; j++) {
if(dsu.get(i * c + j) == i * c + j) {
vec.emplace_back(i * c + j);
}
}
}
int cntc = 0;
for(int &i : vec) {
comp[i] = cntc++;
}
for(int i = 1; i <= r; i++) {
for(int j = 1; j <= c; j++) {
if(i +1 <= r && matrix[i][j] != matrix[i +1][j] && matrix[i][j] != '*' && matrix[i +1][j] != '*') {
adj[comp[dsu.get(i * c + j)]].emplace(comp[dsu.get((i +1) * c + j)]);
}
if(j +1 <= c && matrix[i][j] != matrix[i][j +1] && matrix[i][j] != '*' && matrix[i][j +1] != '*') {
adj[comp[dsu.get(i * c + j)]].emplace(comp[dsu.get(i * c + j +1)]);
}
}
}
queue <pair <int, int>> q;
q.emplace(0, 1);
while(!q.empty()) {
auto [x, d] = q.front();
q.pop();
if(vis[x] != -1) {
continue;
}
vis[x] = d;
for(const int child : adj[x]) {
if(vis[child] == -1) {
q.emplace(child, d +1);
}
}
}
cout << *max_element(vis, vis + 1005 * 1005);
return;
}
signed main() {
#ifndef ONLINE_JUDGE
freopen(".in", "r", stdin);
freopen(".out", "w", stdout);
#endif
ios_base::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
int t = 1; //cin >> t;
for(int i = 1; i <= t; i++) {
solve();
}
return 0;
}
Compilation message (stderr)
zoo.cpp: In function 'void solve()':
zoo.cpp:47:9: warning: unused variable 'cnt' [-Wunused-variable]
47 | int cnt = 0;
| ^~~
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |