Connect nodes to maximize total edge weight

前端 未结 5 1239
情深已故
情深已故 2021-01-01 13:23

I am working on a problem which could be reduced to a graph optimization problem as below.

  • A set of colored nodes is given. They are all unconnected i.e. th

5条回答
  •  太阳男子
    2021-01-01 13:52

    This sounds similar to the 0-1 Knapsack problem where the maximum is calculated if an item is either placed into the knapsack or is not placed into the knapsack. Here is an example:

    def knapsack(numItems, capacity, sizes, values):
      # if no more items left to put in knapsack or knapsack is full
      if (numItems == 0 or capacity == 0):
        return 0
    
      # if can't fit item into knapsack, try the next item
      if (sizes[numItems-1] > capacity):
        knapsack(numItems-1, capacity, sizes, values)
    
      # find the max of including or not including item in knapsack
      return max(
        values[values-1] + knapsack(numItems-1,capacity - weights[numitems-1], sizes, values),
        knapsack(numItems-1, capacity, sizes, values))
    

    Here you are seeking the maximum when a node is either connected with another node or not. When a node is connected, the value that results depends on the node's color. The code would look something like:

    def ConnectNodes(numItems, capacity, sizes, values, nodeColor):
      # if no more items left to connect or capacity is full
      if (numItems == 0 or capacity == 0):
        return 0
    
      # if can't fit item into knapsack, try the next item
      if (sizes[numItems-1] > capacity):
        ConnectNodes(numItems-1, capacity, sizes, values, nodeColor)
    
      # find the max of connecting or not connecting node
      return max(
        RulesForProfit(numItems-1, nodeColor) + ConnectNodes(numItems-1,capacity - weights[numitems-1], sizes, values, nodeColor),
        ConnectNodes(numItems-1, capacity, sizes, values, nodeColor))
    

提交回复
热议问题