对于那些不熟悉不相交集数据结构的人。
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;
}