最小生成树,题目简单。套的Prim模板,其他的题目比较有意义。
Sample Input
3 //村庄个数
1 2 1 //连通情况及权值
1 3 2
2 3 4
4
1 2 1
1 3 4
1 4 1
2 3 3
2 4 2
3 4 5
0
Sample Output //输出最小生成树的权
3
5
1 #include<stdio.h> 2 #include<string.h> 3 #define size 100 4 #define inf 0x3f3f3f3f 5 6 int vellage[size][size],flag[size]; 7 int N,T,a,b,c,i,j,k,ans,maxn; 8 9 void Init() 10 { 11 T=N*(N-1)>>1; 12 memset(flag,0,sizeof(flag)); 13 memset(vellage,0,sizeof(vellage)); 14 } 15 16 int Prim() 17 { 18 ans=0; 19 for(int h=1;h<=N;h++) 20 { 21 maxn=inf; 22 for(i=1;i<=N;i++) 23 { 24 if(flag[i]!=1&&vellage[1][i]<maxn) 25 { 26 maxn=vellage[1][i]; 27 k=i; 28 } 29 } 30 ans+=maxn; 31 flag[k]=1; 32 for(j=2;j<=N;j++) 33 { 34 if(flag[j]!=1&&vellage[k][j]<vellage[1][j]) 35 vellage[1][j]=vellage[k][j]; 36 } 37 } 38 return ans; 39 } 40 41 int main() 42 { 43 while(scanf("%d",&N),N) 44 { 45 Init(); 46 while(T--) 47 { 48 scanf("%d %d %d",&a,&b,&c); 49 vellage[a][b]=vellage[b][a]=c; 50 51 } 52 printf("%d ",Prim()); 53 } 54 return 0; 55 }