Backpack
InterviewTime limit1sMemory limit128 MB
Choose a set of items whose total mass is at most p, where each chosen item requires its named lower-indexed prerequisite to be chosen too.
- Level
Medium6 of 10
- Topics
- Dynamic programming, Tree, Backtracking
- Solved
- No attempts yet
Problem
Hansel and Gretel are setting off on a trip. Hansel, wanting to impress Gretel, decided to pack all of their belongings into a single backpack. What is more, the heavier the backpack is, the better the impression it will make. Of course, Hansel cannot simply cram in everything he finds at home without thinking, because the backpack could tear apart, which would be quite the embarrassment.
On top of that, Hansel must not end up in a situation where, say, he takes the radio but leaves the batteries behind, or takes the tripod but forgets the camera. For each item , Hansel has either named another item without which item would be useless, or simply marked that item is useful on its own.
Help our hero and compute the heaviest backpack contents he can put together, without exceeding the backpack's maximum load and without taking any useless item.
Input
The first line contains two integers and (, ): the number of items Hansel is considering taking, and the load capacity of the backpack in kilograms. If the packed items have a total mass exceeding , the backpack tears.
Assume the items are numbered from to . Each of the next lines describes one item. The description of item consists of two integers and (, ): is the number of the item that must be in the backpack in order to pack item (if , then item may be packed unconditionally), and is the mass of item in kilograms.
Output
Print a single integer: the maximum mass of the backpack contents (in kilograms) that Hansel can achieve.