BEHAPPY - Be Awesome As Barney Stinson


Barney Stinson ;) is way too flirty. He has many girlfriends and he wants to keep all of them happy. He has M girlfriends. He bought N gifts for them. Now he knows that some girlfriends need more gifts and some need less. So he decided that he will give at least Ai gifts and at most Bi gifts to his ith girlfriend. He has to give away all the N gifts. Tell us in how many different ways he can do this.

INPUT

For each test case, first line contains two integers M and N, then follows M lines each having two integers Ai and Bi (1 <= i <= M). Input ends with M and N both equal to 0 and that case should not be processed.

OUTPUT:

For each test case, output the number of different ways in which he can distribute those gifts in a single line.

Constraints

1 <= M <= 20, 1 <= N <= 100, 0 <= Ai, Bi <=100

Example

Input:

3 5
0 1
1 3
1 4
0 0

Output:

6

Explanation

He can distribute 5 gifts in his 3 girlfriends in 6 different ways as follows (0 1 4), (0 2 3), (0 3 2), (1 1 3), (1 2 2), (1 3 1).


hide comments
dhruv2212000: 2019-03-21 06:03:00

Standard DP problem. Here's the hint if barney is giving j gifts to i girls then number of ways he can arrive at this situation can be by giving [j-lower(I th girl) , j - upper(I th girl) ] gifts from total gifts to (i-1)th girl and so on :)

zakir068: 2019-03-02 17:49:45

good problem for the newbies :)

anshuman16423: 2018-09-26 05:51:11

AC in one GO!!! simple DP and recusrsion

egoista_: 2018-06-27 08:51:00

Straight forward dp. AC in one go.

aman_sachin200: 2018-06-15 10:33:53

Same problem UOFTAE!! :P

luka_dzimba911: 2018-03-23 18:23:54

Do not test this problem on spoj toolkit , it gives WA on corner cases

3 3
3 3
0 1
0 1
0 0

should be 1 gives 0

waqar_ahmad224: 2018-03-18 06:19:06

so easy that i solved using only recursion (No dp ) in 1 go , with time 0.00 sec

shahzada: 2017-03-06 04:56:51

Should be moved to tutorial.

kshubham02: 2017-02-22 06:36:06

1. I realized after submitting that I am not even taking multiple test cases. Just inputting M and N once, no breaking at 0 0 or any of that shit.
2. Recursive Solution, should have been TLE because of exponential time complexity.
Result - AC in 0.00s.

So fellas, this question is not about getting ACs. Try and optimize your solutions. Hint - My 'correct' solution runs in O((A[i]-B[i])*M*N).
Spoiler - Think DP.
Suggestion - Try to implement bottom-up.

Last edit: 2017-02-22 06:37:52
.::Austin::.: 2016-07-09 14:07:20

wth!!! exponential passes in 0.00s


Added by:Ankit Kumar Vats
Date:2011-10-21
Time limit:1s
Source limit:50000B
Memory limit:1536MB
Cluster: Cube (Intel G860)
Languages:All except: ASM64
Resource:Inspired