#include<iostream> #include<vector> #include<climits> using namespace std; const int MAXN = 30005; int parent[MAXN], rank_[MAXN]; void make_set(int v) { parent[v] = v; rank_[v] = 0; } int find_set(int v) { if (v == parent[v]) return v; return parent[v] = find_set(parent[v]); } void union_sets(int a, int b) { a = find_set(a); b = find_set(b); if (a != b) { if (rank_[a] < rank_[b]) swap(a, b); parent[b] = a; if (rank_[a] == rank_[b]) ++rank_[a]; cout << "+ " << a << " " << b << endl; } } void disconnect_sets(int a, int b) { a = find_set(a); b = find_set(b); if (a == b) { parent[b] = b; cout << "- " << a << " " << b << endl; } } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n; cin >> n; for (int i = 1; i <= n; i++) make_set(i); int ms, md; cin >> ms; vector<pair<int, int>> molecule(ms); for (int i = 0; i < ms; i++) { cin >> molecule[i].first >> molecule[i].second; } cin >> md; vector<pair<int, int>> target(md); for (int i = 0; i < md; i++) { cin >> target[i].first >> target[i].second; } int licznik = 0; for (int i = 0; i < md; i++) { if (find_set(target[i].first) != find_set(target[i].second)) { licznik++; } } cout << licznik-1 << "\n"; for (int i = 0; i < ms; i++) { if (find_set(molecule[i].first) != find_set(molecule[i].second)) { union_sets(molecule[i].first, molecule[i].second); } } return 0; }
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 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 | #include<iostream> #include<vector> #include<climits> using namespace std; const int MAXN = 30005; int parent[MAXN], rank_[MAXN]; void make_set(int v) { parent[v] = v; rank_[v] = 0; } int find_set(int v) { if (v == parent[v]) return v; return parent[v] = find_set(parent[v]); } void union_sets(int a, int b) { a = find_set(a); b = find_set(b); if (a != b) { if (rank_[a] < rank_[b]) swap(a, b); parent[b] = a; if (rank_[a] == rank_[b]) ++rank_[a]; cout << "+ " << a << " " << b << endl; } } void disconnect_sets(int a, int b) { a = find_set(a); b = find_set(b); if (a == b) { parent[b] = b; cout << "- " << a << " " << b << endl; } } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n; cin >> n; for (int i = 1; i <= n; i++) make_set(i); int ms, md; cin >> ms; vector<pair<int, int>> molecule(ms); for (int i = 0; i < ms; i++) { cin >> molecule[i].first >> molecule[i].second; } cin >> md; vector<pair<int, int>> target(md); for (int i = 0; i < md; i++) { cin >> target[i].first >> target[i].second; } int licznik = 0; for (int i = 0; i < md; i++) { if (find_set(target[i].first) != find_set(target[i].second)) { licznik++; } } cout << licznik-1 << "\n"; for (int i = 0; i < ms; i++) { if (find_set(molecule[i].first) != find_set(molecule[i].second)) { union_sets(molecule[i].first, molecule[i].second); } } return 0; } |