12995 - DP Slayer (hard version)   

Description

The only difference between easy and hard versions are constraints on qai and bi.

There are n items. The weight and value of the i-th item are wi and vi separately.

The total weight of items you can take away is at most m.

There are q queries. In each query, what is the maximum sum of value you can get if you must take the ai-th item and bi-th item?

Input

The first line contains two integers n, m (2 ≤ n ≤ 20, 0 ≤ m ≤ 109) – the number of items and the totol weight you can take away.

Then n lines follow. The i+1-th line contains two integers wivi (0 ≤ wivi ≤ 109) – the weight and value of the i-th item.

Next line contains one integer q (1 ≤ q ≤ 105) – the times of the queries.

Then q lines follow. The i+n+2-th line contains two integers aibi (1 ≤ ai < bi ≤ n) – the two items you must take in the i-th query.

Output

For each query output the maximum sum of value you can get(if there is no legal plan, output 0 instead) and then output a newline('\n').

Sample Input  Download

Sample Output  Download

Tags




Discuss