I solved this problem: A. Ice Skating, Codeforces
My approach was to create grid from given snow drifts coordinates, then convert this grid into graph and then count how many disconnected components are there. The key observation to solve this problem was to see that any disconnected component can be connected with another by using one snow drift, so we also can assume we that we connect everything to the component that contains node 0.
#include <iostream> #include <vector> #include <list> using namespace std; void dfs(vector<list<int>> &adj_list, int node, vector<bool> &visited) { visited[node] = true; for (const int ngbr : adj_list[node]) { if (visited[ngbr]) continue; dfs(adj_list, ngbr, visited); } } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); int n; cin >> n; vector<vector<int>> grid(1000, vector<int>(1000, -1)); int node = 0; for (int i = 0; i < n; ++i) { int x, y; cin >> x >> y; --x; --y; grid[y][x] = node; ++node; } vector<list<int>> adj_list(n, list<int>()); for (int i = 0; i < 1000; ++i) { for (int j = 0; j < 1000; ++j) { if (grid[i][j] == -1) continue; for (int k = 0; k < 1000; ++k) { if (k != j && grid[i][k] != -1) adj_list[grid[i][j]].push_back(grid[i][k]); if (k != i && grid[k][j] != -1) adj_list[grid[i][j]].push_back(grid[k][j]); } } } vector<bool> visited(n); dfs(adj_list, 0, visited); int ans = 0; for (int i = 1; i < n; ++i) { if (!visited[i]) { ++ans; dfs(adj_list, i, visited); } } cout << ans << '\n'; } All test cases passed, but the complexity of this, at least I think so but I'm not very convinced is O(10^6 + 10^5) (or maybe 10^8). That's because the most inner loop will be runned at most 100 times, because the condition will fail most of the time as we have N (<= 100) snow drifts.
It's not something very performant, so I wonder how could I improve time complexity of this?
