1. 程式人生 > >圖論——最小生成樹

圖論——最小生成樹

學習圖論也有好長時間了一些基本的模板再打一遍,今天的是最小生成樹的Kruskal演算法,自己一遍打出來儘管很fake但也是自己一遍打出來的有一點點感悟,Kruskal是運用貪心的思想來實現的先找最小邊 一次一次加入。

#include<iostream>
#include<cmath>
#include<cstring>
#include<string>
#include<ctime>
#include<cstdio>
#include<algorithm>
#include<map>
#include<vector>
#include<stack>
#include<queue>
#include<iomanip>
using namespace std;
inline int  read()
{
	int  x=0,f=1;char ch=getchar();
	while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
	while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
	return x*f;
}
struct bwy 
{
	int x,y,z;
}b[200002];
int ans=0;
int len=1;
int f[5009];
int n,m;
int getfather(int x)
{
	if(x==f[x])
		return x;
	return f[x]=getfather(f[x]);
}
int my(bwy x,bwy y)
{
	return x.z<y.z;
}
void Kruskal()
{
	for(int i=1;i<n;i++)
	{
		for(int j=1;j<=m;j++)
		{
			int xx=getfather(b[j].x);
			int yy=getfather(b[j].y);
			if(xx!=yy)
			{
				f[xx]=yy;
				len++;
				ans+=b[j].z;
			}
			if(len==n)
				return;
		}
	}
}
int main()
{
	//freopen("1.in","r",stdin);
	n=read();m=read();
	for(int i=1;i<=n;i++)
		f[i]=i;
	for(int i=1;i<=m;i++)
	{
		int x,y,z;
		x=read();y=read();z=read();
		b[i].x=x;b[i].y=y;b[i].z=z;
	}
	sort(b+1,b+1+m,my);
	Kruskal();
	if(len==n)printf("%d\n",ans);
	else printf("orz\n");
	return 0;
}

  在這裡本人不是一遍a掉的,tle了原因是少加了 if(len==n) return;這句話導致把全部的邊全部便利了一遍這點要注意!

  背燈和月就花陰,已是十年蹤跡十年心。