Problem
Statement
This problem requires solving the minimum cost of connecting all cities in a city network, a typical minimum spanning tree problem.
Note that each city can only build roads in one direction, so the minimum cost between two cities is not (x + y)/2, but Max (x ,)
The solution is as follows:
UsingSystem;
UsingSystem. Collections. Generic;
UsingSystem. collections;
UsingSystem. text;
// Minimum Spanning Tree Problem
Public ClassCitylink
{
IntN;
Bool[,]
Map;
Bool[]
Visited;
Bool Allconnect ()
{
Visited= New Bool [N]; // Very
Importent !!!!
DFS (0 );
For ( Int I= 0;
I <n; I ++)
If (! Visited [I])
Return False ;
Return True ;
}
Void DFS ( Int I)
{
Visited [I] = True ;
For ( Int J= 0;
J <n; j ++)
If (Map [I, j] &! Visited [J])
DFS (j );
}
Public Int Timetaken ( Int []
X,Int []
Y)
{
N = X. length;
Int [,] D = New Int [N,
N];
Map = New Bool [N,
N];
List int
edgesv = New List int (); // all edges of different lengths
hashtable edges = New hashtable (); // vertex connected to each edge
For ( Int I = 0;
I! = N;
I ++)
For ( Int J= I;
J! = N;
J ++)
{
If (X [I] = x [J])
D [I, j] = (Math. Abs (Y [I] - Y [J])+ 1) / 2;
Else If (Y [I]
= Y [J])
D [I, j] = (Math. Abs (X [I] - X [J]) + 1) / 2;
// Can only go in one direction, but cannot change the direction?
Else
D [I, j] = Math. Max (math. Abs (X [I]- X [J]),
Math. Abs (Y [I] - Y [J]);
// D [I, j] = (math. ABS (X [I]-X [J]) + math. ABS (Y [I]-y [J]) + 1)/2;
If (! Edgesv. Contains (d [I, j])
Edgesv. Add (d [I, j]);
If (Edges. Contains (d [I, j])
{
(List < Int >) Edges [d [I,
J]). Add (I );
(List < Int >) Edges [d [I,
J]). Add (j );
}
Else
{
List < Int >
TMP = New List < Int > ();
TMP. Add (I );
TMP. Add (j );
Edges. Add (d [I, j], TMP );
}
}
Edgesv. Sort ();// KruskalAlgorithmStart with the smallest edge, so sort it here
// Kruskal
For (Int I = 0;
I <edgesv. Count; I ++)
{
// Conect two points
List < Int >
Points = (List <Int >) Edges [edgesv [I];
For ( Int J = 0;
J <points. Count; j + = 2)
{
Map [points [J], points [J + 1]= True ;
Map [points [J + 1], points [J] = True ;
}
If (Allconnect ())
Return Edgesv [I];
}
Return -1;
}
>
Ecogiser's blog