Problem Description
漳州市政府调查乡村交通状况,得到的统计表中列出了任意两村庄间的距离。市政府的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可),并要求铺设的公路总长度为最小。请计算最小的公路总长度。
Input
测试输入包含若干测试用例。每个测试用例的第1行给出村庄数目N(N<100)和M;随后的M行对应村庄间的距离,每行给出一对正整数,分别是两个村庄的编号,以及此两村庄间的距离。为简单起见,村庄从1到N编号。
当N、M为0时,输入结束,该用例不被处理。
Output
对每个测试用例,在1行里输出最小的公路总长度,如果未能找到请输出"no found!"。
Sample Input
3 3 1 2 1 1 3 2 2 3 4 4 6 1 2 1 1 3 4 1 4 1 2 3 3 2 4 2 3 4 5 0 0
Sample Output
3 5
#include <iostream>
#include <stdlib.h>
#define maxvex 20
#include<stdio.h>
using namespace std;
typedef struct {
int adjvex;
} ArcNode1,ArcNode[maxvex][maxvex];
typedef struct {
ArcNode arc;
int vertexnum,arcnum;
char vexs[maxvex];
} Graph;
typedef struct {
int adjvex;
int lowcost;
} ShortEdge[maxvex];
void CreatUDG(Graph& G,int n,int e) {
G.vertexnum=n;
G.arcnum=e;
for(int i=0; i<G.vertexnum; i++) {
for(int j=0; j<G.vertexnum; j++) {
G.arc[i][j].adjvex=999;
}
}
for(int i=0; i<G.arcnum; i++) {
int a,b,w;
cin>>a>>b>>w;
a--;
b--;
G.arc[a][b].adjvex=w;
G.arc[b][a].adjvex=w;
}
}
ShortEdge shortEdge;
void init(int v,Graph G) {
for(int i=0; i<G.vertexnum; i++) {
if(i!=v) {
shortEdge[i].adjvex=v;
shortEdge[i].lowcost=G.arc[v][i].adjvex;
}
}
}
int MinEdge(Graph G,int v) {
int min=999;
int min_i=-1;
for(int i=0; i<G.vertexnum; i++) {
if(i!=v) {
if(shortEdge[i].lowcost>0&&shortEdge[i].lowcost<min) {
min=shortEdge[i].lowcost;
min_i=i;
}
}
}
return min_i;
}
void Judge(Graph G,int v) {
bool unable[maxvex];
bool flag=true;
for(int i=0; i<maxvex; i++) {
unable[i]=false;
}
for(int i=0; i<G.vertexnum; i++) {
for(int j=0; j<G.vertexnum; j++) {
if(G.arc[i][j].adjvex!=999) {
unable[i]=true;
break;
}
}
}
for(int i=0; i<G.vertexnum; i++) {
if(unable[i]==false) {
flag=false;
}
}
if(!flag) {
cout<<"no found!"<<endl;
} else {
int sum=0;
init(v,G);
shortEdge[v].lowcost=0;
for(int i=1; i<G.vertexnum; i++) {
int k=MinEdge(G,v);
// cout<<k<<endl;
// cout<<"("<<G.vexs[shortEdge[k].adjvex]<<","<<G.vexs[k]<<")"<<shortEdge[k].lowcost<<endl;
// cout<<shortEdge[k].adjvex<<endl;
sum+=shortEdge[k].lowcost;
shortEdge[k].lowcost=0;
for(int j=0; j<G.vertexnum; j++) {
// if(i!=k) {
if(shortEdge[j].lowcost>G.arc[k][j].adjvex) {
shortEdge[j].lowcost=G.arc[k][j].adjvex;
shortEdge[j].adjvex=k;
// }
}
}
}
cout<<sum<<endl;
}
}
int main() {
int n,e;
while(cin>>n>>e) {
if(n==0&&e==0)return 0;
Graph G;
CreatUDG(G,n,e);
Judge(G,0);
}
return 0;
}