题目:
解法:
此题是典型的最小生成树问题,题意为建设可以通向每个村庄的道路的最小花费,所以我们需要先对
数据按花费排序,然后再最小生成树就行了,生成树的同时加上花费就可以了。
#include<cstdio>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<queue>
#define ll long long
using namespace std;
struct node
{
int from;
int to;
int cost;
}a[10010];//道路花费
int tree[10010];
bool cmp(node a,node b)
{
return a.cost<b.cost;
}
int fun(int n)
{
int m=n;
while(tree[n]!=n)n=tree[n];
tree[m]=n;//压缩路径
return n;//返回根
}
int main()
{
int n,m;
while(~scanf("%d%d\n",&n,&m))
{
for(int i=0;i<=n;i++)tree[i]=i;//指向自己的即为只有根节点的树,创建森林
for(int i=0;i<m;i++)
cin >> a[i].from >> a[i].to >> a[i].cost;
sort(a,a+m,cmp);//按花费从小到大排序
int ans=0,cnt=0;
for(int i=0;i<m;i++)
{
int t1=fun(a[i].from),t2=fun(a[i].to);
if(t1!=t2)
{
tree[t1]=t2;//将t1的根节点接到t2的根节点上面
ans+=a[i].cost;//加上花费
cnt++;//通过多少路了
}
}
if(cnt==n-1)printf("%d\n",ans);
else printf("Impossible\n");
}
}