In Sheldor's empire, the cities form a tree with cities as vertices and roads as edges. He wishes to choose a capital among his cities and to do that, his ministers come up with the following definition:
Which is the only central city in this empire?
Input File: Link
Input Constraints and Details:
This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try
refreshing the page, (b) enabling javascript if it is disabled on your browser and,
finally, (c)
loading the
non-javascript version of this page
. We're sorry about the hassle.
Step 1. Let's call map ∈ N 9 8 × 2 the input file. Let's call M ∈ N 1 0 0 × 1 0 0 a matrix in which m i j ∈ M is the distance from city i to city j . It's clear that m i j = m j i . So, each row of map represents cities that are directly connected. For example,
map ( 1 , : ) = [ 1 2 ] ⟹ m 1 2 = m 2 1 = 1
In other terms, I'm giving value 1 to m i j if [ i j ] is a row of map . We can continue this process for all 9 8 rows of map . For the sake of coherence, m i j = 0 if i = j .
Now, let's look at M ( 1 , : ) . We see that m 1 2 = m 1 4 = m 1 5 = m 1 9 = m 1 , 1 1 = m 1 , 1 2 = m 1 , 4 2 = m 1 , 4 8 = 1 ) . This means that 1 is directly connected with 2 , 4 , 5 , 9 . . . and so on. Let's look at M ( 2 , : ) . We'll find that m 2 1 = m 2 3 = m 2 , 1 9 = m 2 , 3 9 = m 2 , 7 7 = 1 ) . This means that 2 is directly connected with 1 (we already knew that) 3 , 1 9 , 3 9 and 7 7 . But this means that city 1 has distance 2 from cities 3 , 1 9 , 3 9 , namely
m 1 3 = m 1 , 1 9 = m 1 , 3 9 = m 1 , 7 7 = 2 .
So, this is the algorithm main structure after Step 1 :
Step 2.
We do this procedure for 1 ≤ i ≤ 1 0 0 . After i = 1 0 0 we check if there are any m i j = 0 ∈ M for i = j . If there aren't any, Step 2. ends. If there are still some, we repeat Step 2. for d = d + 1 .
At the end we'll have a matrix M in which only the elements on the diagonal are zero. Eventually we find the maximum value of each row of M
max ( M ( i , : ) ) = ⎣ ⎢ ⎢ ⎢ ⎡ max ( m 1 , j ) max ( m 2 , j ) ⋮ max ( m 1 0 0 , j ) ⎦ ⎥ ⎥ ⎥ ⎤
and than we seek for the row in which there's the minimum of max ( M ( i , : ) ) . It cames out to be 1 .
Here's the MATLAB code for this algorithm.