Kruskal based on Greedy Algorithm

Hello,everyone,see you again.Yesterday I showed you the single source shortest path,and today I want to show you the Kruskal based on greedy algorithm.The difficulity of this solution is how to judge the circle.I use a father number to solve it.If two points father is the same.It means that the new line will create a circle.I am really glad that I pass the code quickly,which is really good to me.However,I still think that my code is not simple enough.And the solution of the sort is bubble sort.We can using sort in STL,which is much simpler and quicker.
Have fun coding,i_human.Have fun coding,everyone!
Now i am going to have a good sleep!

THE CODE:

// Kruskal.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<iostream>
#define a1 100

using namespace std;

struct pot
{
	int one;
	int second;
	int length;
};

int main()
{
	pot d;
	int sum=0;
	int point,line;
	int on,sec,len;
	pot a[a1];
	int b[a1];
	int c[a1+1];
	cin>>point>>line;
	for(int i=0;i<line;i++)
	{
		cin>>on>>sec>>len;
		a[i].length=len;
		a[i].one=on;
		a[i].second=sec;
	}
	for(int i=0;i<line;i++)
		for(int j=0;j<line-i-1;j++)
		{
			if(a[j].length>=a[j+1].length)
			{
				d=a[j];
				a[j]=a[j+1];
				a[j+1]=d;
			}
		}
	for(int i=0;i<line;i++)
		b[i]=0;
	for(int i=1;i<=point;i++)
		c[i]=-1;
	for(int i=0;i<line;i++)
	{
		if(c[a[i].one]==-1&&c[a[i].second]==-1)
		{
			if(a[i].one<a[i].second)
			{
				c[a[i].one]=a[i].one;
				c[a[i].second]=a[i].one;
			}
			else
			{
				c[a[i].second]=a[i].second;
				c[a[i].one]=a[i].second;
			}
			b[i]=1;
		}
		if(c[a[i].one]==-1&&c[a[i].second]!=-1)
		{
			c[a[i].one]=c[a[i].second];
			b[i]=1;
		}
		if(c[a[i].second]==-1&&c[a[i].one]!=-1)
		{
			c[a[i].second]=c[a[i].one];
			b[i]=1;
		}
		if(c[a[i].one]!=-1&&c[a[i].one]!=c[a[i].second]&&c[a[i].second]!=-1)
		{
			if(c[a[i].one]<c[a[i].second])
			{
				for(int k=1;k<=point;k++)
				{
					if(c[k]==c[a[i].second])
						c[k]=c[a[i].one];
				}
			}
			else
			{
				for(int l=1;l<=point;l++)
					if(c[l]=c[a[i].one])
						c[l]=c[a[i].second];
			}
			b[i]=1;
		}
	}
	for(int i=0;i<line;i++)
	{
		if(b[i]==1)
		{
			cout<<a[i].one<<a[i].second<<endl;
			sum=sum+a[i].length;
		}
	}
	cout<<sum;
	system("pause");
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值