1. 程式人生 > >Kruskal based on Greedy Algorithm

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;
}