这是一道考察“并查集”的题目
并查集只有并和查这两种操作
值得注意的是,因为查的操作是O(height)的,所以我们可以依靠一些小技巧降低树的高度,并且不增加时间复杂度
#include <iostream> using namespace std; bool check(int x, int y); void connect(int x, int y); int father(int x); int *a; int main() { int n; cin >> n; a = (int *)malloc((n + 1)*sizeof(int)); for (int i = 1; i <= n; i++){ a[i] = i; } char get; int x, y; while ( cin>>get , get != ‘S‘){ if (get == ‘C‘){ cin >> x >> y; if (check(x, y) == true){ cout << "yes" << endl; } else{ cout << "no" << endl; } } else if (get == ‘I‘){ cin >> x >> y; connect(x, y); } } int count = 0; for (int i = 1; i <= n; i++){ if (a[i] == i){ count++; } } if (count == 1){ cout << "The network is connected." << endl; } else{ cout << "There are " << count << " components." <<endl; } cin >> n; } bool check(int x, int y) { if (father(x) == father(y)){ return true; } else{ return false; } } void connect(int x, int y) { int fx = father(x), fy = father(y); if (fx != fy){ a[fy] = fx; } return; } int father(int x) { if (a[x] == x){ return x; } return a[x] = father(a[x]); //这就是巧妙的地方,如果x在树中很深,这种操作使其直接连接到父亲节点上,节省了很多时间 }
时间: 2024-10-11 00:34:27