Weights Division (hard version)
Easy and hard versions are actually different problems, so we advise you to read both statements carefully.You are given a weighted rooted tree, vertex $$$1$$$ is the root of this tree. Also, each edge has its own cost.A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex $$$v$$$ is the last different from $$$v$$$ vertex on the path from the root to the vertex $$$v$$$. Children of vertex $$$v$$$ are all vertices for which $$$v$$$ is the parent. A vertex is a leaf if it has no children. The weighted tree is such a tree that each edge of this tree has some weight.The weight of the path is the sum of edges weights on this path. The weight of the path from the vertex to itself is $$$0$$$.You can make a sequence of zero or more moves. On each move, you select an edge and divide its weight by $$$2$$$ rounding down. More formally, during one move, you choose some edge $$$i$$$ and divide its weight by $$$2$$$ rounding down ($$$w_i := \left\lfloor\frac{w_i}{2}\right\rfloor$$$).Each edge $$$i$$$ has an associated cost $$$c_i$$$ which is either $$$1$$$ or $$$2$$$ coins. Each move with edge $$$i$$$ costs $$$c_i$$$ coins.Your task is to find the minimum total cost to make the sum of weights of paths from the root to each leaf at most $$$S$$$. In other words, if $$$w(i, j)$$$ is the weight of the path from the vertex $$$i$$$ to the vertex $$$j$$$, then you have to make $$$\sum\limits_{v \in leaves} w(root, v) \le S$$$, where $$$leaves$$$ is the list of all leaves.You have to answer $$$t$$$ independent test cases.
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow.The first line of the test case contains two integers $$$n$$$ and $$$S$$$ ($$$2 \le n \le 10^5; 1 \le S \le 10^{16}$$$) — the number of vertices in the tree and the maximum possible sum of weights you have to obtain. The next $$$n-1$$$ lines describe edges of the tree. The edge $$$i$$$ is described as four integers $$$v_i$$$, $$$u_i$$$, $$$w_i$$$ and $$$c_i$$$ ($$$1 \le v_i, u_i \le n; 1 \le w_i \le 10^6; 1 \le c_i \le 2$$$), where $$$v_i$$$ and $$$u_i$$$ are vertices the edge $$$i$$$ connects, $$$w_i$$$ is the weight of this edge and $$$c_i$$$ is the cost of this edge.It is guaranteed that the sum of $$$n$$$ does not exceed $$$10^5$$$ ($$$\sum n \le 10^5$$$).
For each test case, print the answer: the minimum total cost required to make the sum of weights paths from the root to each leaf at most $$$S$$$.
import sys, threading
from math import inf
input = sys.stdin.readline

def put():
    return map(int, input().split())

def dfs(tree, i, sum, p):
    if len(tree[i]) == 1 and i != 0:
        return 1
    cnt = 0
    for (j, w, c) in tree[i]:
        if j != p:
            z = dfs(tree, j, sum + w, i)
            cnt += z
            if c == 1:
                one.append((w, z))
            else:
                two.append((w, z))
    return cnt

def solve():
    t = int(input())
    for _ in range(t):
        (n, w) = put()
        tree = [[] for i in range(n)]
        for i in range(n - 1):
            (x, y, z, c) = put()
            (x, y) = (x - 1, y - 1)
            tree[x].append((y, z, c))
            tree[y].append((x, z, c))
        dfs(tree, 0, 0, -1)
        (s, flag) = (0, True)
        (diffone, difftwo) = ([], [])
        for arr in [one, two]:
            for i in range(len(arr)):
                s += arr[i][0] * arr[i][1]
            while arr:
                (i, j) = arr.pop()
                while i > 0:
                    if flag:
                        diffone.append((i - i // 2) * j)
                    else:
                        difftwo.append((i - i // 2) * j)
                    i //= 2
            flag = False
        diffone.sort(reverse=True)
        difftwo.sort(reverse=True)
        (s, cnt) = (s - w, inf)
        for i in difftwo:
            s -= i
        (p, q) = (len(diffone), len(difftwo))
        (i, j) = (q - 1, 0)
        while i >= -1:
            while s > 0 and j < p:
                s -= diffone[j]
                j += 1
            if s <= 0:
                cnt = min(cnt, 2 * i + j + 2)
            if i > -1:
                s += difftwo[i]
            i -= 1
        print(cnt)
(one, two) = ([], [])
max_recur_size = 10 ** 5 * 2 + 1000
max_stack_size = max_recur_size * 500
sys.setrecursionlimit(max_recur_size)
threading.stack_size(max_stack_size)
thread = threading.Thread(target=solve)
thread.start()
import sys, threading
from math import inf
input = sys.stdin.readline

def put():
    return map(int, input().split())

def dfs(tree, i, sum, p):
    if len(tree[i]) == 1 and i != 0:
        return 1
    cnt = 0
    for (j, w, c) in tree[i]:
        if j != p:
            z = dfs(tree, j, sum + w, i)
            cnt += z
            if c == 1:
                one.append((w, z))
            else:
                two.append((w, z))
    return cnt

def solve():
    t = int(input())
    for _ in range(t):
        (n, w) = put()
        tree = [[] for i in range(n)]
        for i in range(n - 1):
            (x, y, z, c) = put()
            (x, y) = (x - 1, y - 1)
            tree[x].append((y, z, c))
            tree[y].append((x, z, c))
        dfs(tree, 0, 0, -1)
        (s, flag) = (0, True)
        (diffone, difftwo) = ([], [])
        for arr in [one, two]:
            for i in range(len(arr)):
                s += arr[i][0] * arr[i][1]
            while arr:
                (i, j) = arr.pop()
                while i > 0:
                    if flag:
                        diffone.append((i - i // 2) * j)
                    else:
                        difftwo.append((i - i // 2) * j)
                    i //= 2
            flag = False
        diffone.sort(reverse=True)
        difftwo.sort(reverse=True)
        (s, cnt) = (s - w, inf)
        for i in difftwo:
            s -= i
        (p, q) = (len(diffone), len(difftwo))
        (i, j) = (q - 1, 0)
        while i >= -1:
            while s > 0 and j < p:
                s -= diffone[j]
                j += 1
            if s <= 0:
                cnt = min(cnt, 2 * i + j + 2)
            if i > -1:
                s += difftwo[i]
            i -= 1
        print(cnt)
(one, two) = ([], [])
max_recur_size = 10 ** 5 * 2 + 1000
max_stack_size = max_recur_size * 500
sys.setrecursionlimit(max_recur_size)
threading.stack_size(max_stack_size)
thread = threading.Thread(target=solve)
thread.start()
import io
import os
import heapq
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def get_str():
    return input().decode().strip()

def rint():
    return map(int, input().split())

def oint():
    return int(input())

def dfs(cur):
    stack = [cur]
    while stack:
        cur = stack[-1]
        if v[cur] == 0:
            v[cur] = 1
            for (ni, nw, _) in adj[cur]:
                if v[ni]:
                    continue
                stack.append(ni)
        else:
            if cur != 1 and len(adj[cur]) == 1:
                ret = 1
            else:
                ret = 0
            for (ni, nw, cc) in adj[cur]:
                if v[ni] == 1:
                    w[cur] = nw
                    c[cur] = cc
                    continue
                ret += lc[ni]
            lc[cur] = ret
            if c[cur] == 1:
                if w[cur]:
                    sl1.append((lc[cur] * (w[cur] // 2) - lc[cur] * w[cur], cur))
            elif w[cur]:
                sl2.append((lc[cur] * (w[cur] // 2) - lc[cur] * w[cur], cur))
            v[cur] = 2
            stack.pop()
t = oint()
for _ in range(t):
    (n, s) = rint()
    adj = [[] for i in range(n + 1)]
    v = [0] * (n + 1)
    lc = [0] * (n + 1)
    w = [0] * (n + 1)
    c = [1] * (n + 1)
    sl1 = []
    sl2 = []
    for i in range(n - 1):
        (vv, uu, ww, cc) = rint()
        adj[vv].append((uu, ww, cc))
        adj[uu].append((vv, ww, cc))
    dfs(1)
    sum_ = 0
    for item in sl1:
        i = item[1]
        mul = lc[i]
        sum_ += mul * w[i]
    for item in sl2:
        i = item[1]
        mul = lc[i]
        sum_ += mul * w[i]
    heapq.heapify(sl1)
    heapq.heapify(sl2)
    cost = 0
    while sum_ > s:
        if not sl1:
            item = heapq.heappop(sl2)
            i = item[1]
            mul = lc[i]
            cost += 2
            sum_ = sum_ + item[0]
            w[i] //= 2
            if w[i] != 0:
                heapq.heappush(sl2, (mul * (w[i] // 2) - mul * w[i], i))
            continue
        if not sl2:
            item = heapq.heappop(sl1)
            i = item[1]
            mul = lc[i]
            cost += 1
            sum_ = sum_ + item[0]
            w[i] //= 2
            if w[i] != 0 or len(sl1) == 0:
                heapq.heappush(sl1, (mul * (w[i] // 2) - mul * w[i], i))
            continue
        if sl1[0][0] + sum_ <= s:
            cost += 1
            break
        if sl2[0][0] + sum_ <= s:
            cost += 2
            break
        item1 = heapq.heappop(sl1)
        i = item1[1]
        mul = lc[i]
        diff2 = mul * (w[i] // 2 // 2) - mul * (w[i] // 2)
        if sl1:
            diff = min(diff2, sl1[0][0])
        else:
            diff = diff2
        item2 = sl2[0]
        if item2[0] < item1[0] + diff:
            cost += 2
            heapq.heappush(sl1, item1)
            i = item2[1]
            mul = lc[i]
            sum_ = sum_ + item2[0]
            w[i] //= 2
            heapq.heappop(sl2)
            if w[i] != 0:
                heapq.heappush(sl2, (mul * (w[i] // 2) - mul * w[i], i))
        else:
            cost += 1
            sum_ = sum_ + item1[0]
            w[i] //= 2
            if w[i] != 0:
                heapq.heappush(sl1, (diff2, i))
    print(cost)