最小生成树 A

dalao视频:https://www.bilibili.com/video/av4768483

                   https://www.bilibili.com/video/av4768483?p=2

省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可)。经过调查评估,得到的统计表中列出了有可能建设公路的若干条道路的成本。现请你编写程序,计算出全省畅通需要的最低成本。

Input测试输入包含若干测试用例。每个测试用例的第1行给出评估的道路条数 N、村庄数目M ( < 100 );随后的 N
行对应村庄间道路的成本,每行给出一对正整数,分别是两个村庄的编号,以及此两村庄间道路的成本(也是正整数)。为简单起见,村庄从1到M编号。当N为0时,全部输入结束,相应的结果不要输出。
Output对每个测试用例,在1行里输出全省畅通需要的最低成本。若统计数据不足以保证畅通,则输出“?”。
Sample Input

3 3
1 2 1
1 3 2
2 3 4
1 3
2 3 2
0 100

Sample Output

3
?



#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <algorithm>
using namespace std;
typedef long long ll;
const int maxn=111;
int n,m;
struct node
{
	int from,to,cost;
}exa[maxn];

int father[maxn]; 

void init()
{
	for(int i=1;i<=n;i++) father[i]=i;
}

int findx(int x)
{
	return father[x]==x?x:father[x]=findx(father[x]);
}

void unite(int a,int b)
{
	int x=findx(a);
	int y=findx(b);
	if(x==y) return ;
	father[x]=y;
}

bool same(int x,int y)
{ 
    return findx(x)==findx(y);
}

bool cmp(const node &a,const node &b)
{
	return a.cost<b.cost;
}

ll kruskal()
{
	ll res=0;
	sort(exa+1,exa+1+n,cmp);
	for(int i=1;i<=n;i++)
	{
		if(same(exa[i].from,exa[i].to)) continue;
		unite(exa[i].from,exa[i].to);
		res+=exa[i].cost;
	}
	return res;
}


int main()
{
	while(scanf("%d%d",&n,&m)!=EOF&&n)
	{
		init();
		for(int i=1;i<=n;i++)
		scanf("%d%d%d",&exa[i].from,&exa[i].to,&exa[i].cost);
		ll res=kruskal();
		for(int i=2;i<=m;i++)//判断是不是连通 
		{
			if(!same(1,i)) res=-1;
		}
		if(res==-1) printf("?
");
		else printf("%I64d
",res);
	}
	return 0;
}

  

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <queue>
#include <vector>
using namespace std;
typedef long long ll;
const int maxn=111;
int n,m;
struct node
{
	int to;
	ll cost;
	node(int to,ll cost) : to(to),cost(cost){}
	bool operator<(const node& a)const{
	    return a.cost<cost;
	}
};

std::priority_queue<node>que;
std::vector<node> g[maxn];

bool vis[maxn];

ll prim()
{
	ll res=0;
	vis[1]=1;
	for(int i=0;i<g[1].size();i++) que.push(g[1][i]);
	while(que.size())
	{
		node e=que.top();que.pop();
		if(vis[e.to]) continue;
		vis[e.to]=1;
		res+=e.cost;
		for(int i=0;i<g[e.to].size();i++) que.push(g[e.to][i]);
	}
	return res;
}

int main()
{
    while(scanf("%d%d",&n,&m)!=EOF&&n)
	{
		for(int i=0;i<=m;i++) g[i].clear();
		while(que.size()) que.pop();
		memset(vis,0,sizeof(vis));
		for(int i=1;i<=n;i++)
		{
			int u,v;
			ll cost;
			scanf("%d%d%I64d",&u,&v,&cost);
			g[u].push_back(node(v,cost));
			g[v].push_back(node(u,cost));
		}
		ll res=prim();
		for(int i=1;i<=m;i++) if(!vis[i]) res=-1;
		if(res==-1) printf("?
");
		else printf("%I64d
",res);
	}	
	return 0;
} 

  

原文地址:https://www.cnblogs.com/EchoZQN/p/10383557.html