![]() |
VOOZH | about |
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:
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:
Below is the implementation of the above approach:
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).