time limit: 1 sSpace restriction: 128000 Ktitle level: Golden GoldTitle Description
Description
There are n cities in a country. A number of cities have a telephone line connection, now to increase the M-line (telephone line of course is two-way), so that any two cities directly or indirectly through other cities have telephone line connection, your program should be able to find the minimum cost and a connection scheme.
Enter a description
Input Description
The first line of the input file is the value of N (n<=100).
The second row to the N+1 line is a n*n matrix, the number of rows J of row I, if 0, indicates that city I has a telephone line connection with the city J, otherwise the connection cost between the two cities (range not exceeding 10000).
Output description
Output Description
The first behavior of the output file is the total number of phone lines you connect M, the second line to the m+1 behavior each phone line that you connect, the format is I J, (I<j), I J is the two cities connected by the telephone line. Output follow the prim algorithm to discover the sequential output of each edge, starting at 1.
Line m+2 is the total cost of connecting these telephone lines.
Sample input
Sample Input
5
0 15 27) 6 0
15 0 33) 19 11
27 33 0) 0 17
6 19 0) 0 9
0 11 17) 9 0
Sample output
Sample Output
2
1 4
2 5
17
Data range and Tips
Data Size & Hint
n<=100
1#include <iostream>2#include <cstdio>3#include <cstring>4 using namespacestd;5 structnode{6 int from;7 intto ;8 intlonglist;9}edge[ the];Ten intCnt=0, n,map[ -][ -],l[102][2],dis[ the],vis[102],s[101],u[101]; One intMain () A { -scanf"%d",&n); - thememset (DIS,0x3f,sizeofdis); - - for(intI=1; i<=n;i++) - for(intj=1; j<=n;j++) +scanf"%d",&map[i][j]); - + intk=0; Adis[1]=0;//dis[] Array stores the minimum distance from 1 to that point at - for(intI=1; i<=n;i++) - { -k=0; - for(intj=1; j<=n;j++) - if(vis[j]==0&&DIS[K]>DIS[J])//Vis[j]==0 has not been visited inK=j;//dis[k]>dis[j] Select the smallest point to update -S[i]=k;//s stores the first few sides tovis[k]=1;//Mark this point is used + //Select the smallest blue dots to mark them as white points - for(intj=1; j<=n;j++) the if(vis[j]==0&&dis[j]>Map[j][k]) * { $dis[j]=Map[j][k];Panax Notoginseng //Prim Small Template - if(j<k) thel[j][0]=j,l[j][1]=K; + Elsel[j][0]=k,l[j][1]=J; A } the } + inttot=0, sum=0;i=1;i<=n;i++ for (int), {dis[s[i]]!=0), tot++;49 u[to T]=s[i];50 sum+=dis[s[i]];51}52} -printf"%d\n", tot); Wu for(intI=1; i<=tot;i++)printf ("%d%d\n", l[u[i]][0],l[u[i]][1]); Aboutprintf"%d\n", sum); $ return 0; -}
Idea: See the code in the idea, and the topic given the connected line is not necessarily in the smallest spanning tree, (the title did not let you have to use these Ah!) Why not choose a small one! ~) Red Section Code must be well understood
This problem prim algorithm good dozen, but I think the edge, the output edge is still a certain difficulty
Codevs 1003 Telephone Connection