Water Supply Optimization Problem
Given N houses in a village, determine the minimum cost to supply water to all houses either by building wells in the houses or by connecting them with pipes.
Explanation:
For each house i, you can build a well directly with a cost specified in the array WELLS[i]
. Alternatively, you can connect two houses HOUSE1
and HOUSE2
using a pipe with a cost given in the array PIPES[i] = [HOUSE1, HOUSE2, COST]
. Connections are bidirectional.
Input:
The first line of input contains an integer 'T' representing the number of test cases.
For each test case:
- The first line contains two integers ‘N’ and ‘K’ indicating the number of houses and the number of pipes respectively.
- The next line contains N space-separated integers denoting the cost of wells WELLS[i]
for each house.
- The following K lines each contain three space-separated integers PIPES[i][0]
, PIPES[i][1]
, and PIPES[i][2]
indicating the two houses to connect and the cost of connecting them.
Output:
For each test case, output the minimum total cost needed to supply water to all houses, each on a new line.
Example:
Input:
2
3 2
1 2 2
1 2 1
2 3 1
4 4
3 2 1 4
1 2 5
1 3 3
2 4 4
3 4 2
Output:
3
7
Constraints:
1 ≤ T ≤ 100
1 ≤ N ≤ 10^2
0 ≤ WELLS[i] ≤ 10^5
1 ≤ K ≤ 10000
1 ≤ PIPES[i][0], PIPES[i][1] ≤ N
0 ≤ PIPES[i][2] ≤ 10^5
PIPES[i][0] ≠ PIPES[i][1]
Determine the optimal cost for each test case under the given constraints.

AnswerBot
4mo
Determine the minimum cost to supply water to all houses in a village by building wells or connecting them with pipes.
Iterate through all possible connections and choose the minimum cost between build...read more
Help your peers!
Add answer anonymously...
Samsung Software Developer Intern interview questions & answers
A Software Developer Intern was asked 7mo agoQ. Suppose an array of length n sorted in ascending order is rotated between 1 and ...read more
A Software Developer Intern was asked 7mo agoQ. What are the ACID properties in DBMS?
A Software Developer Intern was asked Q. Sum of Digits Problem Statement Given an integer 'N', continue summing its digit...read more
Popular interview questions of Software Developer Intern
A Software Developer Intern was asked 6mo agoQ1. Suppose an array of length n sorted in ascending order is rotated between 1 and ...read more
A Software Developer Intern was asked 6mo agoQ2. What are the ACID properties in DBMS?
A Software Developer Intern was asked Q3. Sum of Digits Problem Statement Given an integer 'N', continue summing its digit...read more
Stay ahead in your career. Get AmbitionBox app


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
AmbitionBox Awards
Get AmbitionBox app

