问一下这份带码算不算Kruskal最小生成树算法?
查看原帖
问一下这份带码算不算Kruskal最小生成树算法?
549911
林志艺楼主2022/8/15 13:57

AC了,但觉得这像最小生成树,问一问:

#include <algorithm>
#include <iostream>
#include <string>
using namespace std;
struct xyt
{
	int x,y,t;
};
xyt XT[200005];
int n,m,father[1005],fx,fy,ans,num;
bool cmp(xyt LZY,xyt XSE)
{
	return LZY.t<XSE.t;
}
int find(int x)
{
	if(x==father[x])
	{
		return x;
	}
	return father[x]=find(father[x]);
}
void join(int x,int y)
{
	fx=find(x);
	fy=find(y);
	father[fy]=fx;
}
int main()
{
	cin >> n >> m;
	for(int i=0;i<=n;i++)
	{
		father[i]=i;
	}
	for(int i=0;i<m;i++)
	{
		cin >> XT[i].x >> XT[i].y >> XT[i].t;
	}
	sort(XT,XT+m,cmp);
	for(int i=0;i<m;i++)
	{
		fx=find(XT[i].x);
		fy=find(XT[i].y);
		if(fx!=fy)
		{
			father[fy]=fx;
			n--;
		}
		if(n==1)
		{
			cout << XT[i].t;
			return 0;
		}
	}
	cout << -1;
	return 0;
}

它算最小生成树算法吗?

2022/8/15 13:57
加载中...