Time Limit:1000MS Memory Limit:32768KB 64bit IO Format:%I64d & %I64u
Description
ice_cream’s world becomes stronger and stronger; every road is built as undirected. The queen enjoys traveling around her world; the queen’s requirement is like II problem, beautifies the roads, by which there are some ways from every city to the capital. The project’s cost should be as less as better.
Input
Every case have two integers N and M (N<=1000, M<=10000) meaning N cities and M roads, the cities numbered 0…N-1, following N lines, each line contain three integers S, T and C, meaning S connected with T have a road will cost C.
Output
If Wiskey can’t satisfy the queen’s requirement, you must be output “impossible”, otherwise, print the minimum cost in this project. After every case print one blank.
Sample Input
2 1 0 1 10 4 0
Sample Output
10 impossible
简单的最小生成树问题,用并查集来做。
#include<cstdio>
#include<string.h>
#include<algorithm>
using namespace std;
int ans;
int father[],rank[];//父节点,深度记录(这道题没必要用深度记录)
//int max1;
struct Line{
int first;
int last;
int cost;
}line[];//还没学会用数组来记录边,还是在用结构体做的,编程风格有待提高
int cmp(Line a,Line b){return a.cost<b.cost;}//排序的依据函数
int find(int x)//找点的父节点,把一条边的点搞到一个集合里面
{
if(father[x]!=x)
{
father[x]=find(father[x]);//这里有个优化,不会出现长链的情况,直接把father[x]=find[father[x]];
}
return father[x];
}
bool Union(int a,int b)//合并集合
{
int a1=find(a),b1=find(b);
if(a1==b1) return false;//如果是同一个父亲节点的,return false;
else{
father[b1]=a1;//否则合并成一个集合
ans++;
rank[a1]+=rank[b1];
if(max1<rank[a1]) max1=rank[a1];
return true;
}
} int main()
{
int a,b,c,n,m;
while(scanf("%d%d",&n,&m)!=EOF)
{
for(int i=;i<n;i++)
{
father[i]=i;
rank[i]=;
}
for(int i=;i<=m;i++)
{
scanf("%d %d %d",&a,&b,&c);
line[i].first=a;
line[i].last=b;
line[i].cost=c; }
sort(line+,line+m+,cmp);
max1=;
int sum=;
ans=;
for(int i=;i<=m;i++)
{
if(Union(line[i].first,line[i].last))
sum+=line[i].cost;
}
if(ans==n-) printf("%d\n",sum);
else printf("impossible\n");
printf("\n");
}
return ;
}