Friday, 25 September 2015

**Merge List

Merge List

Problem Statement
Shashank is very excited after learning about the linked list. He learned about how to mergetwo linked lists. When we merge two linked lists, the order of the elements of each list doesn't change. For example, if we merge [1,2,3] and [4,5,6][1,4,2,3,5,6] is a valid merge, while [1,4,3,2,5,6] is not a valid merge because 3 is appears before 2.
Shashank wants you to solve a problem for him: You are given two lists having sizes N and M. How many ways can we merge both the lists? It is given that all N+M elements are distinct. As your answer can be quite large, Shashank wants you to print it mod109+7.
Input Format 
The first line contains an integer T, the number of test cases. 
Each of the next T lines contains two integers N and M.
Output Format 
Print the value of the answer mod109+7.
Constraints
1T10 
1N100 
1M100
Sample Input
1
2 2
Sample Output
6
Explanation
Suppose the two lists are [1,2] and [3,4]. The different ways of merging these lists are given below:
[1,2,3,4] 
[1,3,2,4] 
[3,4,1,2] 
[3,1,4,2] 
[1,3,4,2] 
[3,1,2,4]

------------------------------------editorial------------------------------------
You have to merge two lists having sizes `M` and `N`. This is equivalent to arranging `M` objects of one kind and `N` objects of another kind in a row, which is a standard problem in combinatorics. The number of ways of doing it is `(N+MN)`The calculation can be done using dynamic programming, or the concept of modular inverse. 
-----------------------------code-----------------------------------------------
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#define ll long long int
#define mod 1000000007

ll powmod(ll a,ll b)
    {
    b=mod-2;
    ll result=1;
    while(b)
        {
        if(b&1)
            result=(result*a)%mod;
        b=b>>1;
        a=(a*a)%mod;
    }
    return result;
}
int main() {

    int t,n,m,i;
    ll fact[201];
    fact[0]=fact[1]=1;
    for(i=2;i<201;i++)
        fact[i]=(fact[i-1]*i)%mod;
    scanf("%i",&t);
    while(t--)
        {
        scanf("%i%i",&n,&m);
        ll ans=fact[n+m]*powmod((fact[n]*fact[m])%mod,mod);
        printf("%lli\n",ans%mod);
    }
    return 0;
}

No comments:

Post a Comment