08-Figure 7 Highway Village Pass (30 min)
The statistical tables of existing inter-village roads list the costs of several roads that may be built into standard roads, so that each village has the minimum cost required for road connectivity.
Input format:
Input data including number of towns positive integersN≤1000) and number of candidate roadsM (≤3N); the subsequent m-line corresponds to m-path, each row gives 3 positive integers, respectively, the number of two towns directly connected to the road and the budgeted cost of the road reconstruction. For simplicity, towns are numbered from 1 to N.
Output format:
The minimum cost of exporting village pass is required. If the input data is not sufficient to ensure smooth, then output −1, indicating the need to build more roads.
Input Sample:
6 151 2 51 3 31 4 71 5 41 6 22 3 42 4 62 5 22 6 63 4 63 5 13 6 14 5 104 6 85 6 3
Sample output:
12
1#include <cstdio>2#include <cstring>3#include <iostream>4#include <stack>5#include <Set>6#include <map>7#include <queue>8#include <algorithm>9 using namespacestd;Ten structedge{ One intU,v,val,next; A }; -Edge e[3005]; - inth[1005],f[1005]; the intFINDF (inta) { - if(f[a]!=a) { -f[a]=findf (F[a]); - } + returnF[a]; - } + BOOLcmp (Edge A,edge b) { A returna.val<B.val; at } - intMain () { - //freopen ("D:\\input.txt", "R", stdin); - intN,m,i,j,u,v,num; -scanf"%d%d",&n,&m); - for(i=1; i<=n;i++){ inf[i]=i; - } to for(i=0; i<m;i++){ +scanf" %d%d%d",&u,&v,&num); -E[i].val=num; thee[i].v=v; *e[i].u=u; $ }Panax NotoginsengSort (e,e+m,cmp); - intCount=N; the intsum=0; + for(i=0;i<m&&count>1; i++){ Au=e[i].u; thev=e[i].v; + intfu=findf (u); - intfv=findf (v); $ if(fu!=FV) { $ if(fu>FV) { -f[fv]=Fu; - } the Else{ -f[fu]=FV;Wuyi } thecount--; -sum+=E[i].val; Wu } - } About if(count==1){ $printf"%d\n", sum); - } - Else{ -printf"-1\n"); A } + return 0; the}
pta08-Figure 7 Road Village Pass (30 points)