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

xiaoxiao2021-02-28  49

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

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

Hint

///Prim #include <bits/stdc++.h> using namespace std; const int inf=0x3f3f3f; int Map[1100][1100],v[1100],lowcost[1100]; int n,m,sum,flag; void Prim() { int k; for(int i=2; i<=n; i++) lowcost[i]=Map[i][1]; for(int i=2; i<=n; i++) { int temp=inf; for(int j=2; j<=n; j++) { if(lowcost[j]<temp&&!v[j])///注意只要条件中有lowcost[j]的比较就要同时保证v[j]为0 { k=j; temp=lowcost[j]; } } if(temp==inf) { flag=1; return; } else { sum+=temp; v[k]=1;///注意加入一个点k后让v[k]=1; for(int j=2; j<=n; j++) { if(lowcost[j]>Map[j][k]&&!v[j]) lowcost[j]=Map[j][k]; } } } return; } int main() { int x,y,z; while(scanf("%d%d",&n,&m)!=EOF) { sum=flag=0; memset(Map,inf,sizeof(Map)); memset(lowcost,0,sizeof(lowcost)); memset(v,0,sizeof(v)); for(int i=0; i<m; i++) { scanf("%d%d%d",&x,&y,&z); if(Map[x][y]>z) Map[x][y]=Map[y][x]=z; } v[1]=1; Prim(); if(flag==1) printf("-1\n"); else printf("%d\n",sum); } return 0; } ///Kruskal #include <bits/stdc++.h> using namespace std; int n,f[1001]; struct node { int u,v,w; } e[1001]; bool cmp(struct node a,struct node b) { return (a.w<b.w); } void init() { for(int i=1; i<=n; i++) { f[i]=i; } } int getf(int u) { int x=u; while(f[x]!=x) { x=f[x]; } int i=u,j; while(i!=x) { j=f[i]; f[i]=x; i=j; } return x; } int merge(int u,int v) { int t1=getf(u); int t2=getf(v); if(t1!=t2) { f[t1]=t2; return 0; } return 1; } int main() { int i,m,num,sum; while(scanf("%d%d",&n,&m)!=EOF) { num=0; sum=0; init(); for(i=0; i<m; i++) { scanf("%d%d%d",&e[i].u,&e[i].v,&e[i].w); } sort(e,e+m,cmp); for(i=0; i<m; i++) { if(!merge(e[i].u,e[i].v)) { num++; sum+=e[i].w; } if(num==n-1) break; } if(num==n-1) printf("%d\n",sum); else printf("-1\n"); } return 0; }
转载请注明原文地址: https://www.6miu.com/read-59452.html

最新回复(0)