knowing how to check permutations of an array
how modular arithmetic works
Every route starts and ends at country , and between the starting country and ending country , we must visit every other country (). Notice that every pair of different routes have the same starting and ending country (country ) and the order of countries in between are permutations of each other.
For example, imagine two different routes and in a case where :
The first and last country in the both route is . But the countries in between ( for route and for route ) are permutations of each other. There is exactly different possible routes in total, since there are permutations of countries i.e. countries in between the first and last country in a route.
The cost of each route will be , because we are taking the cost modulo . Notice that the value of is quite small, . So if we check different routes, there must be at least two different routes which have the same cost modulo (according to the Pigeonhole Principle). If we want to have three different routes with the same cost modulo , we have to check at most different routes. For , the number of different routes is , so we will always find three such routes.
So, the solution is to keep checking the cost of each and every route. While doing this, if we already find three routes with the same cost modulo , we can just print the routes and be done. If we don’t find any such routes, there isn’t and solution for this, so the answer is No. Since it is always guaranteed to find an answer for , we will have to check at most different permutations for the routes.
where denotes the number of operations needed to find the next permutation of a list. If we use the C++ STL next_permutation, the complexity becomes .