c++并查集实现

#include 
#include 
#include 

std::map mergeSearch;
std::multimap graph;

void init()// 测试数据
{
    graph.insert(std::pair (1,2));
    graph.insert(std::pair (2,3));
    graph.insert(std::pair (5,6));
    graph.insert(std::pair (4,7));

}

int cnt(0);
void mark()
{
    for(auto a:graph)//三种情况 节点两个都不存在,第一个存在和第二个存在
    {
        if(mergeSearch[a.first] == 0 && mergeSearch[a.second] == 0)
            {
                mergeSearch[a.first]  = ++cnt;
                mergeSearch[a.second]  = cnt;
            }

        else if(mergeSearch[a.first] == 0 && mergeSearch[a.second])
            mergeSearch[a.first] = mergeSearch[a.second];
        else 
            mergeSearch[a.second] = mergeSearch[a.first];
    }
}
int main()
{
    init();
    mark();
    for(auto x:mergeSearch)
    {
        std::cout<<"节点"<

你可能感兴趣的:(c++)