1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| void dfs(int idx, int res, vector<bool>& visited, vector<set<int> >& group, const vector<vector<int> >& vp, const vector<vector<int> >& vl) { visited[idx] = true; int len = vp[idx].size(); for (int i = 0; i < len; ++i) { int lan = vp[idx][i]; group[res].insert(lan); for (int j = 0; j < vl[lan].size(); ++j) { int p = vl[lan][j]; if (visited[p] == 0) dfs(p, res, visited, group, vp, vl); } } }
int main() { int n, m, k; cin >> n >> m >> k; vector<vector<int> > vp(n+1); vector<vector<int> > vl(m+1); vector<bool> visited(n+1, false); vector<set<int> > group(n+1); int res = 0; for (int i = 0; i < k; ++i) { int t1, t2; cin >> t1 >> t2; vp[t1].push_back(t2); vl[t2].push_back(t1); } for (int i = 1; i <= n; ++i) { if (!visited[i]) { dfs(i, res, visited, group, vp, vl); ++res; } } for (int i = 0; i < res; ++i) { if (group[i].size() == 0) ++cnt; } if (cnt == res) ++res; cout << res - 1 << endl; return 0; }
|