4

对于那些不熟悉不相交集数据结构的人。

https://en.wikipedia.org/wiki/Disjoint-set_data_structure

我正在努力寻找答案。来自给定朋友组的朋友组及其关系。当然,毫无疑问,这可以使用 BFS/DFS 轻松实现。但是我选择使用不相交集,我也倾向于找到该人所属的朋友组等,并且不相交集听起来确实适合这种情况。

我已经实现了不相交集数据结构,现在我需要找到它包含的不相交集的数量(这会给我组数)。

现在,我坚持如何有效地找到不相交集的数量,因为朋友的数量可以大到 1 00 00 0。

我认为应该有效的选项。

  1. 将新套装附在原件背面,并销毁旧套装。

  2. 在每个工会中更改每个元素的父级。

但是由于朋友的数量很大,我不确定这是否是正确的方法,也许是否有任何其他有效的方法或者我应该继续实施上述任何方法。

这是我的代码以获取更多详细信息。(我没有在这里实现计数不相交集)

//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;
}
4

2 回答 2

8

a,b不相交集数据结构中两个项目的每个联合操作有两种可能的情况:

  1. 您试图将同一组中的项目合并。在这种情况下,什么都不做,不相交集的数量保持不变。
  2. 您将两个不同集合中的项目合并在一起,因此您基本上将两个集合融合为一个 - 有效地将不相交集合的数量减少了一个。

由此,我们可以得出结论,通过跟踪上述类型(2)的并集数,很容易找到每个时刻不相交集的数量。
如果我们用 来表示这个数字succ_unions,那么每个点的集合总数是number_of_initial_sets - succ_unions

于 2015-06-17T22:05:17.247 回答
6

如果您只需要知道不相交集的数量而不是它们是什么,那么一种选择是将计数器变量添加到您的数据结构中,计算有多少不相交集。最初,有n 个,每个元素一个。每次执行联合操作时,如果两个元素没有相同的代表,那么您知道您正在将两个不相交的集合合并为一个,因此您可以减少计数器。看起来像这样:

if (pu != pv){ //if not in the same set.
    numDisjointSets--;  // <--- Add this line
    mst.push_back(graph[i]);
    total += graph[i].first;
    parent[pu] = parent[pv]; // create the link between these two sets
}

希望这可以帮助!

于 2015-06-17T22:04:30.957 回答