您的位置:首页 > 其它

HDU_2122_Ice_cream’sWorldIII

2016-02-20 21:55 411 查看


Ice_cream’s world III

Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)

Total Submission(s): 1487 Accepted Submission(s): 509



Problem 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


Author

Wiskey

Source

HDU 2007-10 Programming Contest_WarmUp

Recommend

威士忌

求最小生成树的权值

kruskal

#include <iostream>
#include <stdio.h>
using namespace std;

#include <string.h>
#include <algorithm>

const int MV=1005;  //最大点数
const int ME=20010;//最大边数
//并查集部分
int uf[MV];         //并查集使用
int uf_find(int x)
{
if(uf[x]==-1)
return x;
return uf[x]=uf_find(uf[x]);
}

struct Edge
{
int fr,to,va;
}edge[ME];//向前星存储边的信息,fr起点/to终点/va权值

int nne;//控制加边的边数,加边前赋值为0
void addedge(int fr,int to,int va)
{
edge[nne].fr=fr;
edge[nne].to=to;
edge[nne++].va=va;
}
bool cmp(Edge a,Edge b)
{//排序函数,讲边按照权值从小到大排序
return a.va<b.va;
}

int Kruskal(int nv)
//传入点数,返回最小生成树的权值,如果不连通返回-1
//O(ElogE+E)
{
memset(uf,-1,sizeof(uf));
sort(edge,edge+nne,cmp);
int cnt=0;         //计算加入的边数
int ans=0;         //最小权值
for(int i=0;i<nne;i++)
{
int fr=edge[i].fr;
int to=edge[i].to;
int va=edge[i].va;
int t1=uf_find(fr);
int t2=uf_find(to);
if(t1!=t2)
{
ans+=va;
uf[t1]=t2;    //并查集merge操作
cnt++;
}
if(cnt==nv-1)
break;
}
if(cnt<nv-1)
return -1;//不连通
return ans;
}

int main()
{
int N,M;
while(scanf("%d%d",&N,&M)!=EOF)
{
nne=0;
while(M--)
{
int a,b,va;
scanf("%d%d%d",&a,&b,&va);
addedge(a,b,va);
addedge(b,a,va);
}
int ans=Kruskal(N);
if(ans==-1)
printf("impossible\n\n");
else
printf("%d\n\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: