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
| using namespace std; int parent[5000] = { 0 }; int rank[5000] = { 0 }; int person, relative, ask; void initializeparent() { for (int i = 0; i < person; i++) { parent[i] = -1; ::rank[i] = 0; } } int find_parent(int x) { int x_root = x; while (parent[x_root] != -1) { x_root = parent[x_root]; } return x_root; } int union_(int x, int y) { int x_root = find_parent(x); int y_root = find_parent(y); if (x_root == y_root) return 0; if (::rank[x_root] > ::rank[y_root]) { parent[y_root] = x_root;//请注意这里一定是这样而不是parent[y] = x;这是血一般的教训啊QAQ } else if (::rank[x_root] < ::rank[y_root]) { parent[x_root] = y_root; } else { parent[x_root] = y_root; ::rank[y_root]++; } return 1; } int main() { int a, b; cin >> person >> relative >> ask; initializeparent(); for (int i = 0; i < relative; i++) { cin >> a >> b; union_(a, b); } for (int i = 0; i < ask; i++) { cin >> a >> b; int x_root = find_parent(a); int y_root = find_parent(b); if (x_root == y_root) cout << "Yes" << endl; else cout << "No" << endl; } return 0; }
|