or a smooth project .
Time limit:4000/2000 MS (java/others) Memory limit:65536/32768 K (java/others)
Total submission (s): 53511 Accepted Submission (s): 24304
problem DescriptionA province investigates the rural traffic situation, and the statistical tables that are obtained list the distances 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.
InputThe test input contains 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.
OutputFor each test case, the minimum road total length is output 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
Note: This example does not have a situation where the minimum spanning tree is not available, so at the end we do not judge whether all nodes belong to the same collection. If this occurs, the step cannot be omitted.
#include <stdio.h> #include <math.h> #include <algorithm> using namespace std;
#define INF 0x3f3f3f3f #define N-th int tree[n];
struct edge{int A, b;
int cost;
BOOL operator< (const edge &a) const{return cost<a.cost;
}}edge[6000];
int findroot (int x)//Find root Node {if (tree[x]==-1) return x;
else{int tmp=findroot (tree[x]);
tree[x]=tmp;
return TMP;
}} int main () {int n,m,i,j;
while (~SCANF ("%d", &n) &&n!=0) {m=n* (n-1)/2;
for (i=1;i<=m;i++) {scanf ("%d%d%d", &edge[i].a,&edge[i].b,&edge[i].cost);
} sort (edge+1,edge+1+m); for (i=1;i<=n;i++) tree[i]=-1;//Initially, all nodes belong to the orphaned collection int ans=0;
int A, B;
for (i=1;i<=m;i++) {a=findroot (EDGE[I].A);
B=findroot (EDGE[I].B);
if (a!=b) {tree[a]=b;
ans+=edge[i].cost;//cumulative this Edge value} } printf ("%d\n", ans);
} return 0; }