HEX (The 8th Shandong Provincial Competition, thinking + number of combinations)

HEX

Problem Description

On a plain of hexagonal grid, we define a step as one move from the current grid to the lower/lower-left/lower-right grid. For example, we can move from (1,1) to (2,1), (2,2) or (3,2).

In the following graph we give a demonstrate of how this coordinate system works.

Your task is to calculate how many possible ways can you get to grid(A,B) from gird(1,1), where A and B represent the grid is on the B-th position of the A-th line.

Input

For each test case, two integers A (1<=A<=100000) and B (1<=B<=A) are given in a line, process till the end of file, the number of test cases is around 1200.

Output

For each case output one integer in a line, the number of ways to get to the destination MOD 1000000007.

Sample Input

1 1
3 2
100000 100000

Sample Output

1
3
1

Hint

Source

"Inspur Cup" Shandong Province 8th ACM College Student Programming Competition (Thanks to Qingdao University of Science and Technology)

Idea: If you can only go to ↙ or ↘, from (1,1)->(x,y), you have to take tot=(x-1) steps in total, and r=(y-1) steps to ↘ , to take l=(xy) steps towards ↙, then the total move is C(tot,r) (or C(tot,l)).
If you can still go to ↓, because one step ↓ is equivalent to one step ↙ plus one step ↘, so if you take i steps to ↓,
In total, just take tot'=(tot-i) steps, r'=(ri) steps towards ↘, and l'=(li) steps towards ↙, (where 0<=i<=min(l,r) ),
Then the total number of moves is C(tot',i)+C(tot'-i,r) (more than one expression).

code:

#include <bits/stdc++.h>
using namespace std;
const int mod = 1e9+7;
typedef long long ll;
ll fac[110000];
void init(){
    fac [0] = fac [1] = 1;
    for(int i = 2; i <= 100000; i++){
       fac [i] = (fac [i-1] * i)% mod;
    }
}
ll q_pow(ll a,ll b){
    ll ans = 1;
    while(b){
        if(b & 1)
            years = years * a % mod;
        b >>= 1;
        a = a * a % mod;
    }
    return ans % mod;
}
ll C(ll n,ll m){
    if(m > n) return 0;
    return fac [n] * q_pow (fac [m] * fac [nm], mod - 2)% mod;
}
ll Lucas(ll n,ll m){
    if(m == 0) return 1;
    else return (C(n%mod,m%mod) * Lucas(n/mod,m/mod)) % mod;
}
int main(){
    init();
    ll x,y;
    while(~scanf("%lld%lld",&x,&y)){
        ll all = x - 1;
        ll r1 = y - 1;
        ll l1 = x - y;
        ll down = min(l1,r1);
        ll ans = 0;
        for(ll i = 0; i <= down; i++){
            ll tot = all - i;
            ll l = l1 - i;
            ll r = r1 - i;
            ans = (ans + Lucas (tot, i)% mod * Lucas (tot-i, l)% mod)% mod;
        }
        printf("%lld\n",ans);
    }
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325872272&siteId=291194637