E2. Distance Tree (hard version)
This version of the problem differs from the previous one only in the constraint on
A tree is a connected undirected graph without cycles. A weighted tree has a weight assigned to each edge. The distance between two vertices is the minimum sum of weights on the path connecting them.
You are given a weighted tree with
Let
For each integer
The first line contains a single integer
The first line of each test case contains a single integer
Each of the next
It is guaranteed that the sum of
For each test case, print

- For
x=1 , we can an edge between vertices1 and3 , thend(1)=0 andd(2)=d(3)=d(4)=1 , sof(1)=1 . - For
x≥2 , no matter which edge we add,d(1)=0 ,d(2)=d(4)=1 andd(3)=2 , sof(x)=2 .