首页 文章

找到图中最大的区域,成本低于m

提问于
浏览
3

我正在尝试找到一种算法,它将给出一个每个边缘具有正成本的无向图,可以连接的最大节点数小于总成本m . 我已经完成了Prim算法的一个版本(命令Nlog(N)),我可以很容易地采用它来查找给定起始节点的最大节点数 . 然而,这可能在该节点不是最佳解决方案的一部分的情况下产生问题 . 我当然可以通过循环遍历每个节点来解决这个问题但是这使得解决方案N ^ 2 * log(N)看起来有点多了 . 有人知道是否有更优化的解决方案吗?

1 回答

  • 0

    这听起来像the Knapsack problem的修改版本 .

    best_vertex = None
    max = 0
    for v in graph.vertices:
        n = largest_area(graph, cost, v)
        if n > max:
            best_vertex = v
            max = n
    
    def largest_area(graph, max_cost, vertex, edges=[]):
        # Base Case
        if max_cost <= 0:
            return edges
    
        # Iterate through all the neighbours and find the highest scoring path.
        max_vertices = 0
        for n in graph.adjacent(vertex):
            edge = graph.get_edge(n, vertex)
            if edge in edges: continue # We've already taken that route.
            num_vertices = largest_area(graph, max_cost - edge.weight, edges + [edge])
            if num_vertices > max_vertices:
                max_vertices = num_vertices
    
        return max_vertices
    

相关问题