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

Автор likecs, история, 8 лет назад, По-английски

A was thinking about a DAG problem. It goes as follows:

You are given a directed acyclic graph with N nodes and M edges. Every vertex has a number associated with it, let us call it A[i]. The power of every vertex is defined as the sum of values written on every vertex reachable from it. We are given Q queries. In each query we need to find the power of a given vertex.

For example, Let N = 5, M = 5 and the value of A = {2, 3, 1, 4, 2}. (Assume 1-based indexing). Let the edges be {(2, 1), (3, 1), (4, 2), (4, 3), (3, 5)}, where (x, y) means there is directed edge from x to y.

So, querying for vertex 4, gives a answer of (2 + 3 + 1 + 4 + 2) = 12, as every vertex is reachable from it, while for vertex 3, it gives answer as (2 + 3 + 2) = 7 as only {1, 3, 5} are reachable from it.

The brute force solution is to perform dfs/bfs in every query. If possible, can you please provide an efficient algorithm for this. (I was thinking about some kind of precomputation using topological sort, but ended but added some values more than once.)

Thank you.

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

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

Is this problem from some online judge?

Provide link if possible.

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

    There is no specific problem on online judge. But this problem is quite similar to it after compressing the SCC's and doing the above operation as stated.

»
8 лет назад, # |
Rev. 5   Проголосовать: нравится -17 Проголосовать: не нравится

Embarrassing solution in EDIT :|

»
8 лет назад, # |
Rev. 3   Проголосовать: нравится -8 Проголосовать: не нравится

I don't see why you cannot do DP on the DAG and cache the answers for every node. The recursion looks like:

for child of node i:
    dfs(child)
    sum[i] += sum[child]

then you just read the sum value at a node you need to query.

Have I misunderstood the problem?

  • »
    »
    8 лет назад, # ^ |
    Rev. 2   Проголосовать: нравится +22 Проголосовать: не нравится

    For a very simple graph like this:

    N = 3, edges between 1 - 2, 1 - 3 and 2 - 3. If your for loop traverses nodes in the order 3, 2 and 1, then A3 will get added twice in answer of 1.

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

An easier task of the very same problem cannot be solved better than O(n * m * bitset), so i doubt the complexity will get any better here.

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

Misunderstood the problem >_<