We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
It can be solved pretty easily by using brute force since the maximum edge cost is pretty small (1023).
The key observation to make is that the answer lies between 1 and 1023, if there is a path from A to B, otherwise -1. So you can just test if it's possible to get from A to B with a cost of 1, 2, 3, ... up to 1023. So all that is left is to create a graph where the OR of all its edges results to the cost you are testing for.
I used a disjoinct set data structure to see if A and B are connected in the resulting graph but I'm pretty sure just doing a DFS from A to see if you can reach B works too.
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Minimum Penalty Path
You are viewing a single comment's thread. Return to all comments →
It can be solved pretty easily by using brute force since the maximum edge cost is pretty small (1023).
The key observation to make is that the answer lies between 1 and 1023, if there is a path from A to B, otherwise -1. So you can just test if it's possible to get from A to B with a cost of 1, 2, 3, ... up to 1023. So all that is left is to create a graph where the OR of all its edges results to the cost you are testing for.
I used a disjoinct set data structure to see if A and B are connected in the resulting graph but I'm pretty sure just doing a DFS from A to see if you can reach B works too.