现有村落间道路的统计数据表中,列出了有可能建设成标准公路的若干条道路的成本,求使每个村落都有公路连通所需要的最低成本。
输入格式:
输入数据包括城镇数目正整数N(≤1000)和候选道路数目M(≤3N);随后的M行对应M条道路,每行给出3个正整数,分别是该条道路直接连通的两个城镇的编号以及该道路改建的预算成本。为简单起见,城镇从1到N编号。
输出格式:
输出村村通需要的最低成本。如果输入数据不足以保证畅通,则输出−1,表示需要建设更多公路。
输入样例:
6 15
1 2 5
1 3 3
1 4 7
1 5 4
1 6 2
2 3 4
2 4 6
2 5 2
2 6 6
3 4 6
3 5 1
3 6 1
4 5 10
4 6 8
5 6 3
输出样例:
12
// // main.cpp // 8-1 公路村村通 // // Created by 佘一夫 on 15/11/18. // Copyright © 2015年 佘一夫. All rights reserved. // #include <iostream> using namespace std; #define N_Max 1002 #define M_Max 3006 #define MaxValue 9999999 typedef struct MGraph *PGraph; struct MGraph { int G[N_Max][N_Max]; int Nv; int Ne; int Flag; }; PGraph CreateGraph(int N,int M) { PGraph Graph=new(MGraph); Graph->Flag=0; Graph->Nv=N; Graph->Ne=M; for (int i=1; i<=Graph->Nv; ++i) { for (int k=1; k<=Graph->Nv; ++k) { Graph->G[i][k]=MaxValue; Graph->G[k][i]=MaxValue; } } return Graph; } int FindMin(int LowCost[],int n) { int j=0,k=0,MinCost=MaxValue; for (k=1,j=1; j<=n; ++j) { if (LowCost[j]&&LowCost[j]<MinCost) { MinCost=LowCost[j]; k=j; } } if (k==1) { return 0; }else { return k; } } void Prim(PGraph Graph,int Parent[]) { int LowCost[N_Max]; for (int i=1; i<=Graph->Nv; ++i) { LowCost[i]=MaxValue; } int i,j,k; for (i=2; i<=Graph->Nv; ++i) { LowCost[i]=Graph->G[1][i]; Parent[i]=1; } LowCost[1]=0; Parent[1]=-1; for (i=2;i<=Graph->Nv; ++i) { k=FindMin(LowCost,Graph->Nv); if (k) { LowCost[k]=0; for (j=2; j<=Graph->Nv; ++j) { if (LowCost[j]&&Graph->G[k][j]<LowCost[j]) { LowCost[j]=Graph->G[k][j]; Parent[j]=k; } } }else { Graph->Flag=1; break; } } } PGraph BuildGraph(PGraph Graph) { int row=0,lie=0,weight=0; for (int i=1; i<=Graph->Ne; ++i) { cin>>row>>lie>>weight; Graph->G[row][lie]=weight; Graph->G[lie][row]=weight; } return Graph; } int Cost(int A[],PGraph Graph) { int temp=0,cost=0; for (int i=2; i<=Graph->Nv; ++i) { temp=A[i]; cost+=Graph->G[i][temp]; } return cost; } int main(int argc, const char * argv[]) { //Input int N=0,M=0,cost=0; cin>>N>>M; PGraph Graph=CreateGraph(N, M); Graph=BuildGraph(Graph); int Parent[N_Max]={0}; Prim(Graph, Parent); if (Graph->Flag==0) { cost=Cost(Parent,Graph); } if (N==1) { cout<<'0'; } else { if (Graph->Flag==0) { cout<<cost; }else{ cout<<"-1"; } } return 0; }