zoukankan      html  css  js  c++  java
  • [Algo] Min Cost to Cut Ropes

    Given n ropes of different lengths, we need to connect these ropes into one rope. We can connect only 2 ropes at a time. The cost required to connect 2 ropes is equal to sum of their lengths. The length of this connected rope is also equal to the sum of their lengths. This process is repeated until n ropes are connected into a single rope. Find the min possible cost required to connect all ropes.

    Example 1:

    Input: ropes = [8, 4, 6, 12]
    Output: 58
    Explanation: The optimal way to connect ropes is as follows
    1. Connect the ropes of length 4 and 6 (cost is 10). Ropes after connecting: [8, 10, 12]
    2. Connect the ropes of length 8 and 10 (cost is 18). Ropes after connecting: [18, 12]
    3. Connect the ropes of length 18 and 12 (cost is 30).
    Total cost to connect the ropes is 10 + 18 + 30 = 58
    

    Example 2:

    Input: ropes = [20, 4, 8, 2]
    Output: 54
    

    Example 3:

    Input: ropes = [1, 2, 5, 10, 35, 89]
    Output: 224
    

    Example 4:

    Input: ropes = [2, 2, 3, 3]
    Output: 20


    import java.util.PriorityQueue;
    
    public class MinCostRope {
        
        public static int getMinCost(int[] ropes) {
            PriorityQueue<Integer> pq = new PriorityQueue<>();
            for (int num : ropes) {
                pq.offer(num);
            }
            int res = 0;
            while (pq.size() > 1) {
                int num1 = pq.poll();
                int num2 = pq.poll();
                int sum = num1 + num2;
                res += sum;
                pq.offer(sum);
            }
            return res;
        }
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            int[] ropes = {2, 2, 3, 3};
            int res = getMinCost(ropes);
            System.out.println(res);
        }
    
    }
  • 相关阅读:
    华丽的NHibernate
    Linq to NHibernate入门示例
    更新部分字段 NHibernate
    Entity Framework 与 面向对象
    开源框架之TAB控件
    MEF插件系统中通信机制的设计和实现
    用CQRS+ES实现DDD
    Unit of work + Repository
    [开源]C#二维码生成解析工具,可添加自定义Logo (转)
    就是这么简单(续)!使用 RestAssuredMockMvc 测试 Spring MVC Controllers(转)
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12640407.html
Copyright © 2011-2022 走看看