Kruscal算法1.2

给定一张图中的顶点及边及边的权值,求连接整张图所用最小花费

1.不使用快排:

#include<bits/stdc++.h>
using namespace std;
struct node
{
    int u;
    int v;
    int w;
} edge[1000];
int pre[10000];
int n,m;
bool cmp(const node&a,const node&b )
{
    return a.w<b.w;
}
int find(int x)
{
    return x==pre[x]?x:pre[x]=find(pre[x]);
}
void unions(int x,int y)
{
    int fx=find(x);
    int fy=find(y);
    if(fx!=fy)
    {
        pre[fx]=fy;
    }
}
void createGraph()
{
    for(int i=1; i<=n; i++)pre[i]=i;
    for(int i=1; i<=m; i++)
    {
        cin>>edge[i].u>>edge[i].v>>edge[i].w;
    }
}
int kruscal()
{
    int ans=0;
    sort(edge+1,edge+m+1,cmp);
    for(int i=1; i<=m; i++)
    {
        if(find(edge[i].u)!=find(edge[i].v))
        {
            unions(edge[i].u,edge[i].v);
            ans+=edge[i].w;
        }
    }
    return ans;
}
int main()
{
    while(cin>>n>>m)
    {
        createGraph();
        cout<<kruscal()<<endl;
    }
}

2.使用快排:

#include<bits/stdc++.h>
using namespace std;
struct edge 
{
	int u;
	int v;
	int w;
};
struct edge e[1000010];
int n,m;
int f[100010]={0},sum=0,count=0;
void quicksort(int left,int right)
{
	int i,j;
	struct edge t;
	if(left>right)
		return;
	i=left;
	j=right;
	while(i!=j)
	{
		while(e[j].w>=e[left].w&&i<j)
			j--;
		while(e[i].w<=e[left].w&&i<j)
			i++;
		if(i<j)
		{
			t=e[i];
			e[i]=e[j];
			e[j]=t;
		}
	}
	t=e[left];
	e[left]=e[i];
	e[i]=t;
	quicksort(left,i-1);
	quicksort(i+1,right);
	return;
}
int getf(int v)
{
	if(f[v]==v)
		return v;
	else
	{
		f[v]=getf(f[v]);
		return f[v];
	}
}
int merge(int v,int u)
{
	int t1,t2;
	t1=getf(v);
	t2=getf(u);
	if(t1!=t2)
	{
		f[t2]=t1;
		return 1;
	}
	return 0;
}
int main()
{
	int i;
	scanf("%d%d",&n,&m);
	for(i=1;i<=m;i++)
		scanf("%d%d%d",&e[i].u,&e[i].v,&e[i].w);
	quicksort(1,m);
	for(i=1;i<=n;i++)
		f[i]=i;
	for(i=1;i<=m;i++)
	{
		if(merge(e[i].u,e[i].v))
		{
			count++;
			sum+=e[i].w;
		}
		if(count==n-1)
			break;
	}
	printf("%d\n",sum);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/lanshan1111/article/details/83210563