栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

最小生成树

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

最小生成树

最小生成树
prim

#include
#define inf 1000000000
using namespace std;
int n,m,dis[5010],ans;
bool b[5010];
int tot,h[5010],nxt[400010],to[400010],cost[400010];
void add(int x,int y,int z)
{
	++tot;
	nxt[tot]=h[x];
	h[x]=tot;
	to[tot]=y;
	cost[tot]=z;
}
struct node{
	int s,i;
	bool operator < (const node &a)const
	{
		return a.s < s;
	}
};
priority_queue qq;
void prim()
{
	memset(dis,63,sizeof(dis));
	node tt; tt.i=1; tt.s=0;
	qq.push(tt); dis[1]=0;
	while(!qq.empty())
	{
		node t=qq.top(); qq.pop();
		int x=t.i; b[x]=1;
		if(t.s != dis[x]) continue;
		for(int i=h[x]; i; i=nxt[i])
			if(!b[to[i]] && dis[to[i]] > cost[i])
			{
				dis[to[i]]=cost[i];
				tt.i=to[i]; tt.s=cost[i];
				qq.push(tt);
			}
	}
}
int main()
{
	scanf("%d%d",&n,&m);
	for(int i=1; i<=m; i++)
	{
		int x,y,z;
		scanf("%d%d%d",&x,&y,&z);
		add(x,y,z); add(y,x,z);
	}
	prim();
	for(int i=1; i<=n; i++)
	{
		if(dis[i] == inf)
		{
			cout<<"orz";
			return 0;
		}
		else ans+=dis[i];
	}
	cout< 

kruskal

#include
#include
#include
#include
#include
using namespace std;
int n,m,i,j,u,v,total;
struct edge{
    int start,to;long long val;
}bian[2000005];
int f[100000];
long long ans;

int find(int x)//并查集部分
{
    if (f[x]==x) return x; else 
    {
        f[x]=find(f[x]);
        return f[x];
    }	
}

bool cmp(edge a,edge b)//结构体快排时用到的
{
    return a.val
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/714954.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号