- Connecting Graph III
Given n nodes in a graph labeled from 1 to n. There is no edges in the graph at beginning.
You need to support the following method:
connect(a, b), an edge to connect node a and node b
query(), Returns the number of connected component in the graph
Example
5 // n = 5
query() return 5
connect(1, 2)
query() return 4
connect(2, 4)
query() return 3
connect(1, 4)
query() return 3
思路:并查集经典题。
代码如下:
class ConnectingGraph3 {
public:
/**
* @param a: An integer
* @param b: An integer
* @return: nothing
*/
ConnectingGraph3(int n) {
father.resize(n + 1);
for (int i = 1; i <= n; ++i) {
father[i] = i;
}
count = n; //total # of connected components
}
void connect(int a, int b) {
int fatherA = find(a);
int fatherB = find(b);
if (fatherA != fatherB) {
father[fatherA] = fatherB; //not father[a] = father[b], not father[a] = fatherB
count--;
}
}
/**
* @return: An integer
*/
int query() {
return count;
}
private:
vector<int> father;
int count;
int find(int x) {
if (father[x] == x) return x;
int x2 = x;
while(x != father[x]) {
x = father[x];
}
//path compression!!!
while(x2 != x) {
int temp = father[x2];
father[x2] = x;
x2 = temp;
}
return x;
}
};
本文介绍了一种使用并查集数据结构解决图连接问题的方法。在一个初始无边的图中,通过connect操作连接节点,并用query操作返回当前图的连通组件数量。示例代码展示了如何实现并查集,包括路径压缩优化,以高效地处理节点连接和查询。
3471

被折叠的 条评论
为什么被折叠?



