数据结构实验之图论六:村村通公路

                                                 数据结构实验之图论六:村村通公路

Time Limit: 1000MS Memory Limit: 65536KB

Problem Description

当前农村公路建设正如火如荼的展开,某乡镇政府决定实现村村通公路,工程师现有各个村落之间的原始道路统计数据表,表中列出了各村之间可以建设公路的若干条道路的成本,你的任务是根据给出的数据表,求使得每个村都有公路连通所需要的最低成本。

Input

连续多组数据输入,每组数据包括村落数目N(N <= 1000)和可供选择的道路数目M(M <= 3000),随后M行对应M条道路,每行给出3个正整数,分别是该条道路直接连通的两个村庄的编号和修建该道路的预算成本,村庄从1~N编号。 

Output

输出使每个村庄都有公路连通所需要的最低成本,如果输入数据不能使所有村庄畅通,则输出-1,表示有些村庄之间没有路连通。 

Example Input

5 8
1 2 12
1 3 9
1 4 11
1 5 3
2 3 6
2 4 9
3 4 4
4 5 6

Example Output

19

01 #include <stdio.h>
02 #include <string.h>
03 #include <stdlib.h>
04 #include <algorithm>
05 using namespace std;
06 struct edge{
07     int u,v,w;
08 }p[3333];
09 int pre[1024],n,m,u,v,i,q,t,cnt,ans;
10 int cmp(edge a,edge b){
11     if(a.w==b.w){
12         if(a.u==b.u)
13             return a.v<b.v;
14         return a.u<b.u;
15     }
16     return a.w<b.w;
17 }
18 int find(int x){
19     t=x;
20     while(t!=pre[t])
21         t=pre[t];
22     while(x!=pre[x])
23         q=pre[x],pre[x]=t,x=q;
24     return x;
25 }
26 int main(){
27     while(~scanf("%d %d",&n,&m)){
28         ans=cnt=0;
29         for(i=1;i<=n;i++)
30             pre[i]=i;
31         for(i=0;i<m;i++)
32             scanf("%d %d %d",&p[i].u,&p[i].v,&p[i].w);
33         sort(p,p+m,cmp);
34         for(i=0;i<m;i++)
35             if(find(p[i].u)!=find(p[i].v))
36                 pre[max(find(p[i].u),find(p[i].v))]=min(find(p[i].u),find(p[i].v)),ans+=p[i].w,cnt++;
37         if(cnt<n-1)
38             ans=-1;
39         printf("%d\n",ans);
40     }
41     return 0;
42 }
原文地址:https://www.cnblogs.com/CCCrunner/p/11782113.html