VOOZH about

URL: https://www.geeksforgeeks.org/dsa/counting-city-trips-with-k-stops/

⇱ Counting City Trips with K Stops - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Counting City Trips with K Stops

Last Updated : 18 Jan, 2024

Given n cities connected by (n-1) roads, each specified by [a, b, type], denoting a connection between cities a and b of a certain 'type' (0 for normal roads, 1 for highways). The task is to count the number of trips satisfying two conditions:

  • The trip must include travel via a highway at least once.
  • The trip must have exactly K city stops along the way.

Return the final result by taking modulo 10^9 + 7. Additionally, it's emphasized that stops during the trip need not be distinct.

Examples:

Input: n = 3, k = 2, roads = {{1, 2, 1}, {2, 3, 0}}
Output:4
Explanation: Possible good trips are:
{1, 2}: start at 1, stop at 2.
{1, 3}: start at 1, don't stop at 2, go directly to 3.
{2, 1}: start at 2, stop at 1.
{3, 1}: start at 3, don't stop at 2, go directly to 1.

Input: n = 5, k = 3, roads = { {1, 2, 1}, {2, 3, 1}, {3, 4, 1}, {4, 5, 0} }
Output: 114
Explanation: All trips are good except - {1, 1, 1}, {2, 2, 2}, {3, 3, 3}, {4, 4, 4}, {5, 5, 5}, {4, 4, 5}, {4, 5, 4}, {4, 5, 5}, {5, 4, 4}, {5, 4, 5}, {5, 5, 4} as they do not involve travelling via a highway.

Approach: This can be solved with the following idea:

Count total number of trips that can be possible by avoiding above mentioned conditions. Then calculate trips made by normal road. Subtract both of them which will led to our desired ans.

Step-by-step approach:

  • Create a adjacency matrix adj for normal roads.
  • Calculate total combination possible by using power function.
  • Iterate over normal roads:
    • As it will help us to find out atleast one highway combinations.
    • Using DFS function, we can find combination possible.
  • Add combination to ans.
  • Return ans.

Below is the implementation of the above approach:


Output
114

Time Complexity: O(V + E), where V is the number of vertices (cities) and E is the number of edges (roads).
Auxiliary Space: O(V), where V is the number of vertices (cities).

Comment