RAINBOW - Rainbow Ride

Mr.Raju and his extended family are on vacation in Chennai. They visit MGM and see the Rainbow ride. They want to enjoy the ride. However, there are some problems.

Each person in the family likes some other people in the family. Each person insists that he or she will go on the ride only if all the people whom that person likes and all the people who like that person also go on the ride. If someone doesn't like anyone and no one likes him, he may come for the ride.

You have been roped in to solve this dilemma. Given the weight of the each person in the family, and the list of people they like, and the maximum weight that the Rainbow can bear safely, calculate the maximum number of people in the family who can go on the rainbow.


There will be multiple test cases in the input. For our convenience the family members are numbered from 1 to n. Each test case begins with a line containing two integers n ( 1 ≤ n ≤ 1000 ) and C ( 0 ≤ C ≤ 1000 ), where n is the number of people in the family and C the maximum capacity of the ride in kilograms.

The next line contains n space separated integers with the ith integer giving the weight of the i th family member. These weights are positive and less than or equal to 200 kilograms. Then n lines follow. Each line contains a sequence of integers separated by spaces. The first integer ki gives the number of people in the family person i likes, followed by the persons i likes. An empty line separates each test case. The end of input is indicated by n=0 and C=0 and it should not be processed.There are atmost 50 test cases.


For each test case output on a separate line the maximum number of persons that can take the ride under the given conditions.


5 200
50 50 50 50 50
1 2
1 3
1 5
1 4

3 200
100 100 100
1 2
1 3
1 1

0 0


hide comments
panther_786: 2020-07-20 14:14:09

AC in one go!
disjoint_set + knapsack = AC.

flyingduchman_: 2016-08-22 12:34:54

Ambiguous language.Should be moved to trash

kshubham02: 2016-07-31 15:19:37

Some Edge cases anyone??

prakhar: 2015-02-20 20:37:40

nice problem with basic algos :)

Daga: 2014-10-04 18:29:47

nice one...multiple thoughts

Aniket Kumar: 2014-01-25 10:06:03

nice combination of knapsack and graph search ..

Ravi Kiran: 2010-07-28 12:44:59

Just a little clarification since it seemed ambiguous to me!
"If someone doesn't like anyone and no one likes him, he may come for the ride (*alone*)."

Last edit: 2010-07-28 12:47:27

Added by:Swarnaprakash
Time limit:1s
Source limit:50000B
Memory limit:1536MB
Cluster: Cube (Intel G860)
Languages:All except: ERL JS-RHINO NODEJS PERL6 VB.NET
Resource:Kurukshetra 09 OPC