제출 #1063741

#제출 시각아이디문제언어결과실행 시간메모리
1063741danielzhuTracks in the Snow (BOI13_tracks)C++17
93.44 / 100
2021 ms1048576 KiB
#include <bits/stdc++.h> using namespace std; #define MX 4001 typedef long long LL; typedef pair<int, int> PR; typedef tuple<int, int, int> TP; const int MOD = (int)1e9 + 7; const int INF = (int)1e9 + 5; const LL MAXV = (LL)1e18; using vi = vector<int>; using vii = vector<vi>; int H, W; string md[MX]; //snow meadow /* use Disjoint Sets to solve the problem. (1) Use BFS to find all CCs (each with the same footprint letter R or F) and assign each CC with an integer ID starting from 0. (2) Perform a scan on the meadow to discover connectitvity between adjcent CCs with different letters (3) A bipartite graph or tree, then BFS to find the height of the tree which is the answer. */ vector<unordered_set<int>> adj; int solve() { cin >> H >> W; //read the snow meadow info for (int i = 0; i < H; i++) cin >> md[i]; if (md[0][0] == '.') return 0; vector<vector<int>> id(H, vector<int>(W, -1)); int t = 0; for (int i = 0; i < H; i++) for (int j = 0; j < W; j++) { if (md[i][j] == '.' || id[i][j] != -1) continue; queue<PR> Q; Q.push({i, j}); id[i][j] = t; //BFS to find the CC while (!Q.empty()) { int r = Q.front().first, c = Q.front().second; Q.pop(); int dr = 0, dc = 1; for (int k = 0; k < 4; k++) { int nr = r + dr, nc = c + dc; if (nr >= 0 && nr < H && nc >= 0 && nc < W && md[nr][nc] == md[i][j] && id[nr][nc] == -1) { id[nr][nc] = t; Q.push({nr, nc}); } swap(dr, dc); dc = -dc; } } t++;//next CC } adj.resize(t); //scan adjacency between CCs, to build the bipartite graph for (int i = 0; i < H; i++) for (int j = 0; j < W; j++) { if (id[i][j] == -1) continue; int dr = 0, dc = 1; for (int k = 0; k < 4; k++) { int r = i + dr, c = j + dc; if (r >= 0 && r < H && c >= 0 && c < W && id[r][c] != -1 && id[r][c] != id[i][j] && md[r][c] != md[i][j]) { adj[id[i][j]].insert(id[r][c]); adj[id[r][c]].insert(id[i][j]); } swap(dr, dc); dc = -dc; } } vector<int> d(t, -1); queue<int> Q2; Q2.push(0); //the root d[0] = 1; while (!Q2.empty()) { int u = Q2.front(); Q2.pop(); for (auto v : adj[u]) if (d[v] == -1) { d[v] = d[u]+1; Q2.push(v); } } return *max_element(d.begin(), d.end()); } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cin.exceptions(cin.failbit); cout << solve() << endl; return 0; }
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...