...

/

Solution: Connecting n Pipes with Minimum Cost

Solution: Connecting n Pipes with Minimum Cost

Review the solution to connecting n pipes with minimum cost in detail.

Solution: Sorting

class Program
{
/// <summary>
/// Calculates the minimum cost of connecting pipes.
/// </summary>
/// <param name="pipes">An array where its length is the number of pipes and indexes are the specific lengths of the pipes.</param>
/// <returns>The minimum cost of connecting the pipes.</returns>
public static int MinCost(int[] pipes)
{
// Create a priority queue out of the given list
PriorityQueue<int> pq = new PriorityQueue<int>();
foreach (int pipe in pipes)
{
pq.Enqueue(pipe);
}
// Initialize result
int cost = 0;
// While size of priority queue is more than 1
while (pq.Count > 1)
{
// Extract shortest two pipes from the priority queue
int first = pq.Dequeue();
int second = pq.Dequeue();
// Connect the pipe: update cost and insert the new pipe to pipes queue
cost += first + second;
pq.Enqueue(first + second);
}
return cost;
}
// Main program to test the above function
public static void Main(string[] args)
{
int[] pipes = new int[] { 4, 3, 2, 6 };
Console.WriteLine(MinCost(pipes)); // Output: 29
}
}

Explanation

If you look at the animation presented in the ...