# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
680018 | yashsingh | Tracks in the Snow (BOI13_tracks) | C++17 | 0 ms | 0 KiB |
This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> pii;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
cin >> n >> m;
vector<vector<char>> g(n, vector<char> (m));
for (int i{0}; i < n; ++i) {
for (int j{0}; j < m; ++j) {
cin >> g[i][j];
}
}
// find max distance from source node to any other node + 1 with nodes being connected components
vector<vector<bool>> visited(n, vector<bool>(m, false));
vector<vector<int>> comp(n, vector<int>(m, -1));
vector<int> dx(4) = {0, 0, 1, -1};
vector<int> dy(4) = {1, -1, 0, 0};
int curcomp{0};
for (int i{0}; i < n; ++i) {
for (int j{0}; j < m; ++j) {
if (visited[i][j] || g[i][j] == '.') continue;
queue<pii> q;
while (!q.empty()) {
pii qtop{q.front()};
if (visited[qtop.first][qtop.second]) continue;
visited[qtop.first][qtop.second] = 1;
comp[qtop.first][qtop.second] = curcomp;
for (int k{0}; k < 4; ++k) {
if (qtop.first + dx[k] < 0 || qtop.first + dx[k] >= n || qtop.second + dy[k] < 0 || qtop.second + dy[k] >= m) continue;
if (visited[qtop.first + dx[k]][qtop.second + dy[k]]) continue;
if (g[qtop.first + dx[k]][qtop.second + dy[k]] != g[i][j]) continue;
q.push({qtop.first + dx[k], qtop.second + dy[k]});
}
}
++curcomp;
}
}
vector<set<int>> graph(n*m);
for (int i{0}; i < n; ++i) {
for (int j{0}; j < m; ++j) {
for (int k{0}; k < 4; ++k) {
if (qtop.first + dx[k] < 0 || qtop.first + dx[k] >= n || qtop.second + dy[k] < 0 || qtop.second + dy[k] >= m) continue;
if (comp[qtop.first][qtop.second] != comp[qtop.first + dx[k]][qtop.second + dy[k]]) {
graph[comp[qtop.first][qtop.second]].insert(comp[qtop.first + dx[k]][qtop.second + dy[k]]);
}
}
}
}
vector<int> dist(curcomp, INT_MAX);
dist[0] = 0;
queue<int> q;
q.push(0);
int ans{0};
while (!q.empty()) {
int qtop{q.front()};
q.pop();
ans = max(ans, dist[qtop]);
for (auto it = graph[qtop].begin(); it != graph[qtop].end(); it = next(it)) {
if (dist[*it] != INT_MAX) continue;
dist[*it] = dist[qtop] + 1;
}
}
cout << ans << "\n";
return 0;
}