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

Автор codehacker4689_p, история, 15 месяцев назад, По-английски

There is an undirected tree T, with edges of length 1. Initially, each of the nodes(1-indexed) stores a value equal to the node number. Shuffle these values among the nodes in such a way that no node stores a value equal to its node number.

There are two values to determine:

1.The minimum possible sum of the distances between the initial and final positions of all values.

2.The maximum possible sum of the distances between the initial and final positions of all values.

Example

T_nodes = 4

T_from= [1, 2, 3]

T_to= [2, 3, 4]

In the minimum distance shuffle, node values are switched with their neighbours. The distance is 1 +1+1+1=4. In the maximum distance shuffle, the distance is 3+1+1+3=8. Return [3, 8].

Constraints

• 1 ≤ T_nodes ≤ 1e5

• 1 ≤ T_from[i], T_to[i] ≤ T_nodes

• T_from[i] ≠ T_to[i]

Seen this in some recent oa and tried alot but not able to solve. Can anyone help please?

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

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

So this is definitely a trie problem. Let's denote any random node n as the root. For each node that borders the root, you want to store its value in the trie. Make sure you assign proper edge weights in the trie. After this, you want to have a prefix sum s and a suffix sum t to sum up the values of the trie nodes. And then the answer to 1 will be the sum of s and t and the answer to 2 will be the absolute difference of s and t.

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

    Can you be little brief about how we store values in trie and do prefix & suffix sum. Thankyou!

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

      Inside of the trie, make sure the edge weights are assigned correctly according to the ratio of the order of the nodes' values in the original tree. This is important, as the value of our trie's vertex + its edges will be what's in our prefix and suffix sums. The prefix sums optimize our O((V + E)^2) solution to an O(V + E) solution, so neglect them if the constraints permit it. No problem, glad to help.

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

    Interesting approach! not so clear how you know where to place each number and why it's optimal:/ sounds like the algorithm works for a fixed permutation, but how do we approach the one with maximum or minimum answer?

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