A greedy problem involving trees where we are "to make things better in the future".
A viable configuration of the given tree can be divided into two trees, each consists of vertices of the same color (if we compress edges and add a dummy root node when needed). Let's call them and , respectively. Note that and are independent of each other with respect to satisfying the conditions. For each vertex in , it must hold that the total weight of 's proper descendants is no more than , and in that case it is always possible make the total weight of vertices in subtree be by setting 's weight appropriately. The same can be said for . Ideally, we can configure the given tree such that in each subtree , the total weight of vertices with a different color than are minimized.
Official editorial:

The hard part of this problem is to understand the highlighted sentence.
code
I find this editorial in Chinese helpful.
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步