Блог пользователя saharshluthra

Автор saharshluthra, история, 4 года назад, По-английски

Hi,

I came with this subproblem while working on something else. Can someone help me understand if it's solvable problem ?


Difficulty: Hard

Design a data structure that maintains a directed graph. A node with node_id=0 is created by default, having no edges. The data-structure supports following queries:

  1. Create() : Create a new node, with node_id assigned from an auto-incrementing counter. Add a directed edge from node-0 to this new node; return node_id of new node.

  2. Add(x, y) : Add a directed edge from node-x to node-y. Ignore if there is already an edge from x to y.

  3. Delete(x, y) : Delete the directed edge from node-x to node-y, and also delete all the nodes (and their edges) of graph which are not reachable from node-0. return the list of deleted edges and nodes.

All APIs should work in amortized complexity O(log(N)) , where N is the number of nodes in the graph at the time of query.

  • Проголосовать: нравится
  • +36
  • Проголосовать: не нравится

»
4 года назад, # |
  Проголосовать: нравится +3 Проголосовать: не нравится

Auto comment: topic has been updated by saharshluthra (previous revision, new revision, compare).

»
4 года назад, # |
  Проголосовать: нравится +3 Проголосовать: не нравится
"an directed graph"
Is it "a directed graph" or "an undirected graph"?
»
4 года назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

Auto comment: topic has been updated by saharshluthra (previous revision, new revision, compare).

»
4 года назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

Lets store two sets for every node V with edges (from; V) and (V; to).

Adding edge U->V: insert V to U's set of "to" vertices and U to V's set of "from" vertices.

Removing U->V: delete same vertices and go recursively to V, if |V's "from" set| = 0.

  • »
    »
    4 года назад, # ^ |
    Rev. 5   Проголосовать: нравится 0 Проголосовать: не нравится

    Assuming From(x) represents the set of all nodes reachable to x and To(x) represents the set of all nodes node-x can reach.

    It has two problems:

    1. Doesn't satisfy time complexity requirement. Consider the query set: {create(); create(); create(); create(); create();.. N times ; add(1,2); add(2,3); add(3,4); add(4,5); ....N-1 times} Time complexity = N^2

    2. Handler of deletion is wrong. What you are suggesting works only in acyclic graph.

»
4 года назад, # |
  Проголосовать: нравится +5 Проголосовать: не нравится

Garbage collector?

  • »
    »
    4 года назад, # ^ |
      Проголосовать: нравится 0 Проголосовать: не нравится

    Nah, unless you want $$$O(N+M)$$$ for operations of type 3 — GC has scheduled passes that erase nodes. It also doesn't forbid duplicate edges.