1,首先将int father[999],初始化:father[n] = n;
2,遍历所有的边,如果x,y节点的祖先节点一样,就证明存在闭环
如果祖先节点不一样,就将y的祖先节点(while(y != father[]y) y = father[y])的父节点设置为x
3,遍历结束后如果每一个x,y的祖先节点都不一样,那么就不存在闭环
#include <bits/stdc++.h>
using namespace std;
int father[999];
int find_father(int e)
{
while(e != father[e]) e = father[e];
return e;
}
int close(map<string,map<string,int>> m)
{
//初始化查并集
for(int i = 0;i < 999;++i) father[i] = i;
multimap<int,pair<string,string>> grap;//存储所以的边
for(auto elem1 : m)
{
for(auto elem2 : elem1.second)
{
grap.insert({elem2.second,{elem1.first,elem2.first}});
}
}
//查并集
for(auto elem : grap)
{
string x = elem.second.first;
string y = elem.second.second;
//判断是否构成闭环
if(find_father(x[0]) == find_father(y[0]))
{
return true;
}
//添加边
father[find_father(y[0])] = x[0];
}
return false;
}
int main()
{
map<string,map<string,int>> m;
for(int i = 0;i < 10;++i)
{
string x,y;
int num;
cin >> x >> y >> num;
m[x].insert({y,num});
m[y].insert({x,num});
}
cout << close(m);
return 0;
}