Problem Description a province to investigate the rural traffic situation, the statistics obtained in the table lists the distance between any two villages. The goal of the provincial government's "unblocked project" is to enable road traffic between any of the two villages in the province (but not necessarily directly connected roads, as long as they can be reached indirectly by road), and require the minimum length of the road to be paved. Please calculate the minimum total length of the road.
The input test inputs contain several test cases. The 1th row of each test case gives the number of villages N (< 100), and the subsequent N (N-1)/2 lines correspond to the distance between the villages, each with a pair of positive integers, the number of two villages, and the distance between the two villages. For the sake of simplicity, the village is numbered from 1 to N.
When n is 0 o'clock, the input ends and the use case is not processed.
Output for each test case, the total length of the road is minimized in 1 rows.
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 Hint Hint Huge input, scanf is recommended.
Source Zhejiang University Computer Postgraduate exam on the machine-2006
#include <stdio.h> int n,map[105][105],s[105],node[105],sum,fn=1000000;
void Set_first (int n)//Initialize {for (int i=1;i<=n;i++) {node[i]=fn; s[i]=0;
0 means not in the S collection for (int j=1;j<=n;j++) MAP[I][J]=FN;
}} void Prim (int stra) {int min,e; sum=0;
S[stra]=1; for (int k=2;k<=n;k++)//k adds K points to the S collection, then K points on a tree {for (int i=1;i<=n;i++)//calculates the weight of the point connected to the selected point if (s[i]=
=0&&node[i]>map[stra][i]) node[i]=map[stra][i];
MIN=FN; for (int i=1;i<=n;i++)//Find the minimum weight of the points connected to the points in the S collection (min>node[i]&&s[i]==0) {min=n Ode[i]; e=i;//record position} s[e]=1; Sum+=min;
Stra=e;//sum is the weight of the point in the S collection} int main () {int a,b,p;
while (scanf ("%d", &n) >0&&n) {Set_first (n);//Initialize for (int i=1;i<=n* (n-1)/2;i++)
{scanf ("%d%d%d", &a,&b,&p);
if (map[a][b]>p)//judging heavy edges {map[a][b]=map[b][a]=p;
}} prim (1);//Calculate printf ("%d\n", sum);
}
}