SUBSHARD - Subset and upset (HARD)

no tags 

The whole world is crazy about subset sum. We define subset sum as sum of all subparts. A subpart is a number which is obtained by erasing certain digits and arranging the remaining numbers in the same order. You have to calculate the subset sum of the given number. Since the number can be very large return the subset sum modulo m.

For example if the number is 1357, then the various subparts are 1, 3, 5, 7, 13, 15, 17, 35, 37, 57, 137, 135, 157, 357, 1357.

Input

First line contains T (1 ≤ T ≤ 50) denoting the number of test cases.

Next T lines containing two numbers n (0 < n < 101000) and m(1 < m < 109).

Output

Print the subset sum modulo m.

Example

Input:
6
111 9
111 200
456 9
456 1000
1357 1000
1357 5000

Output:
3
147
6
618
333
2333

Time Limit ≈ 2*(My Python 3 Program Top Speed)

See also: Another problem added by Tjandra Satria Gunawan


hide comments
[Rampage] Blue.Mary: 2012-10-04 11:06:48

O(n^2) with good optimization CAN pass, even I've finsihed an O(n) program.

:D: 2012-10-04 11:06:48

It can and should be done in O(N).

Zhouxing Shi: 2012-10-04 11:06:48

@Tjandra Satria Gunawan : O(N^2) TLE??????


I think time limit should be 2s~3s.

Last edit: 2012-10-04 04:58:59
:D: 2012-10-04 11:06:48

Thank you! This should be more interesting. Also, you don't have to credit me in the resource. Throwing random ideas around isn't really problem setting ;)

Problem Solver: 2012-10-04 11:06:48

Seems like it's first problem i'm able to solve from you, Tjandra. :-)


Added by:Tjandra Satria Gunawan
Date:2012-10-03
Time limit:1s
Source limit:50000B
Memory limit:1536MB
Cluster: Cube (Intel G860)
Languages:All except: ASM64
Resource:Hard version of NITT5 problem.