Question:
Residents on the island need to build the shortest road to minimize costs
Analysis:
It is actually the minimum spanning tree. You can use primAlgorithmAnd the Kruskal algorithm,
Based on the recently learned Kruskal algorithm, the following is done using the Kruskal algorithm.
The idea of the Kruskal algorithm is:
First, sort all edges in non-descending order to see if each edge can match the previous
The edge of the component ring. If yes, the component is not selected. If not, the component is selected to determine whether the component is a group.
You can use and query the set to implement a loop.
The idea of querying datasets is:
{, 3}, {}, {6, 7, 8}, {9}. When the edge is the currently least edge, the vertex at both ends is
. Because is in two different sets, it cannot form a loop.
Set, such as 1 and 2, because the first must be 1, 2, 3 can be directly or indirectly connected, add edge (1, 2)
You can make the graph a loop, so you can use the followingCodeImplementation and query set: assume edge (u, v)
The edges are fixed at U [I], V [I], and the length is Len [I].
Int find_set (int x)
{
If (x = union_set [x])
Return X;
Return find_set (union_set [x]);
}
The following functions can be implemented in the main function:
Int ans = 0;
For (INT I = 0; I <= CNT; I ++)
Union_set [I] = I;
Int x = find_set (U [I]);
Int y = find_set (V [I]);
If (X! = Y)
{
Union_set [y] = X;
Ans + = Len [I];
}
The answer is ans.
# include
# include
# include
using namespace STD;
# define x 150
int union_set [80]; // query and set
typedef struct node
{// define struct
int U, V, Len; // vertex, vertex, length
}node;
struct node P [X];
int find_set (int x)
{// query the set where the element is located
If (x = union_set [x])
return X;
return find_set (union_set [x]);
}< br> int CMP (const void * a, const void * B)
{// sort by strong conversion to struct, non-descending order by length
struct node * c = (struct node *);
struct node * D = (struct node *) B;
return C-> len-D-> Len;
}< br> int main ()
{< br> freopen ("sum. in "," r ", stdin);
freopen (" sum. out "," W ", stdout);
int N;
while (CIN> N, N)
{< br> int A, B;
char success, CH2;
int CNT = 0;
for (INT I = 0; I {< br> CIN> loss> A;
for (Int J = 0; j {< br> CIN> CH2> B;
P [CNT]. U = bytes-'A';
P [CNT]. V = CH2-'A';
P [CNT]. len = B;
CNT ++;
}< BR >}< br> qsort (p, CNT, sizeof (P [0]), CMP ); // sort
// N forests at the beginning. Each element is the sequence number of the set.
For (INT I = 0; I <= CNT; I ++)
Union_set [I] = I;
Int ans = 0;
For (INT I = 0; I <CNT; I ++)
{
Int x = find_set (P [I]. U); // you can specify the number of the set where the vertex is located.
Int y = find_set (P [I]. V );
If (X! = Y)
{
Union_set [y] = X;
Ans + = P [I]. Len;
}
}
Cout <ans <Endl;
}
Return 0;
}