Cut edges of a rooted binary tree so that at least X resulting components each contain at least K nodes, minimizing total cut cost.
Medium5TreeDynamic programmingDFSGreedyNo attempts yetTime limit2sMemory limit512 MBA human body needs a way to tell safe food from dangerous food. The human tongue detects four kinds of taste: sweet, sour, bitter, and salty. What people call tasty or not tasty comes from the combination of these four tastes and personal preference.
Junpyo cannot taste anything. Seohyun noticed it when Junpyo ate sour kimchi and said it was not sour, and she worried that he would get hurt because he cannot detect dangerous tastes. She started looking into why Junpyo cannot taste, and why he will not admit that his sense of taste is abnormal, and she found that he has N taste buds numbered 1 to N.
Junpyo's taste buds are connected to each other and form a single binary tree rooted at bud 1. One connected clump of buds is one bud group. An ordinary person has at least X bud groups. Taste is a combined sensation, so a bud group works properly only when it holds at least K buds. Seohyun wants to cut connections between buds so that Junpyo, like an ordinary person, ends up with at least X bud groups holding at least K buds each. Bud groups with fewer than K buds may remain. They simply do not count.

Every time a connection is cut, the rest of Junpyo's nervous system takes damage equal to the strength of that connection. If the connection between bud A and bud B affects each of them by 10, cutting it gives Junpyo 10 pain. Junpyo would live an even harder life if his other senses were hurt while his taste came back, so Seohyun wants to minimize the sum of the strengths of the connections she cuts, that is, the total pain Junpyo takes. Find the minimum total pain Junpyo must take to taste again.
The first line contains the number of taste buds Junpyo has, N (1 ≤ N ≤ 5,000), the minimum number of buds one bud group needs to work properly, K (1 ≤ K ≤ 100), and the minimum number of working bud groups needed to taste like an ordinary person, X (1 ≤ X ≤ 100).
Each of the next N−1 lines contains the information of bud i (2 ≤ i ≤ N), namely Pi (1 ≤ Pi ≤ N) and Ci (0 ≤ Ci ≤ 100,000). The parent of bud i is bud Pi, and cutting the connection between the two causes Ci pain. Bud 1 is the root, so no line is given for it.
Print the minimum total pain Junpyo must go through to taste again. If there is no way for him to get his sense of taste back, print -1.
In the second example, cutting the connection between bud 2 and bud 4 gives the smallest total pain.