Dependency Algorithm - find a minimum set of packages to install

前端 未结 10 1905
别那么骄傲
别那么骄傲 2021-02-02 17:23

I\'m working on an algorithm which goal is to find a minimum set of packages to install package \"X\".

I\'ll explain better with an example:



        
10条回答
  •  失恋的感觉
    2021-02-02 17:30

    I actually think graphs are the appropriate structure for this problem. Note that A and (E or C) <==> (A and E) or (A and C). Thus, we can represent X = A and (E or C) with the following set of directed edges:

    A <- K1
    E <- K1
    A <- K2
    C <- K2
    K1 <- X
    K2 <- X
    

    Essentially, we're just decomposing the logic of the statement and using "dummy" nodes to represent the ANDs.

    Suppose we decompose all the logical statements in this fashion (dummy Ki nodes for ANDS and directed edges otherwise). Then, we can represent the input as a DAG and recursively traverse the DAG. I think the following recursive algorithm could solve the problem:

    Definitions:
    Node u - Current Node.
    S - The visited set of nodes.
    children(x) - Returns the out neighbors of x.

    Algorithm:

    shortestPath u S = 
    if (u has no children) {
        add u to S
        return 1
    } else if (u is a dummy node) {
      (a,b) = children(u)
      if (a and b are in S) {
        return 0
      } else if (b is in S) { 
        x = shortestPath a S
        add a to S
        return x
      } else if (a in S) {
        y = shortestPath b S
        add b to S
        return y
      } else {
        x = shortestPath a S
        add a to S
        if (b in S) return x
        else {
            y = shortestPath b S
            add b to S
            return x + y
        }
      }
    } else {
      min = Int.Max
      min_node = m
      for (x in children(u)){
        if (x is not in S) {
          S_1 = S
          k = shortestPath x S_1
          if (k < min) min = k, min_node = x
        } else {
          min = 1
          min_node = x
        }
      }
      return 1 + min
    }
    

    Analysis: This is an entirely sequential algorithm that (I think) traverses each edge at most once.

提交回复
热议问题