Counting zero sum paths in a tree

We are given a tree with nodes N (up to 100,000). Each edge is weighed either +1, or -1, and the nodes are numbered from 1to N. How many disordered pairs (A, B)exist such that on the path A -> X -> B, where X( X != A && X != B) is some vertex on the path between Aand B, the sum of the weights of the edges on the path A -> Xis 0, and the sum of the weights of the edges on the path X -> Bis 0?

From this it follows that we are only interested in the path lengths, otherwise the sum of the weights of the edges cannot be 0. We cannot sort out the potential Aand B, otherwise, we will get a solution O(N^2)that will not work for less than 1 second. Any tips on how to solve it? The program should run for less than 1 second, so the O(N)or solution will work O(N logN).

Edit: However, if we can calculate the number of good paths starting from each node, we can solve the problem. Can this be calculated? Sounds DP-ish to me, but I'm not sure.

+5
source share
2 answers

, O(N^2). . , (O(N) O(NlnN)), O(N^2).

  • node x0 L0.
  • node . , , .
  • .
  • node 2 , 2, L0. , node 3 .
  • ( , ) 1, , node . node, ( 5) .
  • : L0, L1, L2, ..., L0. . m , . . L0, L0, L1, L2, ....

, , O(N^2).

, . , , k1,k2 c, , . , k1+k2, k1*k2, . ​​ , .

: ( -1, 1) ( ).

0

, , -, , : (A,B), . , ( ) A -> ... -> B := d(A,B) = 0,

d(A,B) = d(A,X) + d(X,B) = 0 + 0 = 0

, ; , ( ), Θ (n) . , , , (n/2) * (n-1)/2 , Θ (n ^ 2) n - .

, , Θ (n ^ 2) BFS . , :

, V U, d(A,V) = d(A,U). :

  • A -> ... -> V = A -> ... -> U -> ... -> V, , U (WLOG) A V.

    d(A,V) = d(A,U) + d(U,V) <=> d(A,V) = d(A,V) + d(U,V) <=> d(U,V) = 0

    , U V A, d(U,V) = 0.

  • fork -; , fork K.

    d(A,V) = d(A,K) + d(K,V) <=> d(K,V) = d(A,V) - d(A,K)

    d(A,U) = d(A,K) + d(K,U) <=> d(K,U) = d(A,U) - d(A,K)

    d(U,V) = d(K,U) + d(K,V) = d(A,U) + d(A,V) - 2*d(A,K) = 2*(d(A,U) - d(A,K)) = 2 * d(K,U)

    , U V , , A, A K; , , K. , d(A,U) = d(A,V) d(U,V) = 0 , A , , isn ' t .

, . , , , , ; , O (n ^ 2), BFS . , -, .

-1

All Articles