对于不熟悉不相交集合数据结构的人来说。
https://en.wikipedia.org/wiki/Disjoint-set_data_structure
我正在尝试找出给定朋友和他们之间关系的朋友组数。当然,毫无疑问,这可以很容易地使用BFS / DFS实现。但我选择使用不相交集合,我还倾向于找到人所属的朋友组等,而不相交集合显然非常适合这种情况。我已经实现了不相交集合数据结构,现在我需要找到它包含的不相交集合数量(这将给我组数)。
现在,我卡在了如何有效地找到不相交集合数量上,因为朋友的数量可能达到1 00 00 0。
我认为应该可行的选项:
- 将新集附加在原集的后面,并销毁旧集。
- 在每次合并时更改每个元素的父元素。
这是我的代码以获取更多详细信息。(我在此处未实现计算不相交集合)
//disjoint set concept
//https://www.topcoder.com/community/data-science/data-science-tutorials/disjoint-set-data-structures/
// initially all the vertices are takes as single set and they are their own representative.
// next we see, compare two vertices, if they have same parent(representative of the set), we leave it.
// if they don't we merge them it one set.
// finally we get different disjoint sets.
#includes ...
using namespace std;
#define edge pair<int, int>
const int max 1000000;
vector<pair<int, edge > > graph, mst;
int N, M;
int parent[max];
int findset(int x, int* parent){
//find the set representative.
if(x != parent[x]){
parent[x] = findset(parent[x], parent);
}
return parent[x];
}
void disjoints(){
for(int i=0; i<M; i++){
int pu = findset(graph[i].second.first, parent);
int pv = findset(graph[i].second.second, parent);
if(pu != pv){ //if not in the same set.
mst.push_back(graph[i]);
total += graph[i].first;
parent[pu] = parent[pv]; // create the link between these two sets
}
}
}
void noOfDisjoints(){
//returns the No. of disjoint set.
}
void reset(){
for(int i=0; i<N; i++){
parent[i] = i;
}
}
int main() {
cin>>N>>M; // No. of friends and M edges
int u,v,w; // u= source, v= destination, w= weight(of no use here).
reset();
for(int i =0; i<M ;i++){
cin>>u>>v>>w;
graph.push_back(pair<int, edge>(w,edge(u,v)));
}
disjoints();
print();
return 0;
}