https://www.codechef.com/viewsolution/23724348
My approach is:
- Keep all the Ci in a TreeMap where value C is the key and value will be its count.TreeMap implemenets Self Balancing Tree within itself so it will sort all the values.
- Then, I take the C value of starting city which is 1st city let it be called as X .Pushed it on the stack and then taking the nearest values with respect to X. If there difference is less than equal to D then push it into stack and remove that value from TreeMap.The,nearest values corresponding to X is taken until there is a city in TreeMap which is near to X whose difference is less than D .
- After, doing it for Starting city I pop a value from stack and repeat Step 2 with it until TreeMap is Empty which means all cities are visited or If stack is empty which means we can’t visit any further more cities.