Minimum Travel Cost Problem

You are given a country called 'Ninjaland' with 'N' states, numbered from 1 to 'N'. These states are connected by 'M' bidirectional roads, each with a specified travel cost. The aim is to select exactly 'N' - 1 roads so that a tourist bus can travel to every state at least once, minimizing the total travel cost.

Example:

Input:
Consider a country with 4 states (1 to 4) and 5 bidirectional roads: 
1 --- 2, cost = 8
2 --- 3, cost = 6
3 --- 4, cost = 5
1 --- 4, cost = 2
1 --- 3, cost = 4
Output:
The optimal roads can be selected as follows:
1 --- 4, cost = 2
1 --- 3, cost = 4
2 --- 3, cost = 6
Total minimum travel cost = 12.

Constraints:

  • 1 ≤ 'T' ≤ 10 (Number of test cases)
  • 1 ≤ 'N' ≤ 1000 (Number of states)
  • 'N' - 1 ≤ 'M' ≤ 2000 (Number of roads)
  • 1 ≤ 'C' ≤ 106 (Cost of roads)
  • Time limit: 1 sec
Input:

The first line contains an integer 'T'.
Each test case consists of:
- An integer 'N' and 'M'.
- 'M' lines, each containing three integers 'A', 'B', and 'C'.

Output:

For each test case, print 'N' - 1 lines, each containing three integers 'A', 'B', and 'C' indicating the chosen roads with their costs.

Note:

You do not need to manually print anything as it is handled by the system. Just implement the function to find the minimum cost selection of roads.

AnswerBot
1y

The task is to select 'N' - 1 roads in a country with 'N' states, such that the tourist bus can travel to every state at least once at minimum cost.

  • The problem can be solved using a minimum spanning t...read more

Help your peers!
Select
Add answer anonymously...

Top Software Developer Intern Interview Questions Asked at Amazon

Q. What is the code to calculate the distance between two nodes in a binary tree?
Q. Given a tree, find its diameter (the longest path between two nodes in the tree)...read more
Q. For a given array, how would you count the number of inversions?
Software Developer Intern Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2025 Info Edge (India) Ltd.

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits