Gym - 101498D Counting Paths (推公式)

Counting Paths
time limit per test
1.0 s
memory limit per test
256 MB
input
standard input
output
standard output

A binary tree is a tree data structure in which each node has at most two children, which are referred to as the left child and the right child.

Consider an infinite binary tree with each node has exactly two children, and two given integers a and b, count the number of paths in the infinite binary tree that satisfy the following rules:

  • The path starts from the root of the tree.
  • The length of the path is equal to a (The length of a path is the total number of edges from the root to the final node on that path).
  • The number of change of direction along the path is equal to b. Change of direction means, going to your right child if you are the left child of your parent or vise versa.

As the number of paths can be too large, print it (modulo 109 + 7).

Input

The first line of the input contains an integer T (1 ≤ T ≤ 105), where T is the number of the test cases.

Each test case has one line that contains two integers a and b (0 ≤ b < a ≤ 105), the length of the path and the number of change of direction along it.

Output

For each test case, print a single integer that represents the number of paths that satisfy the mentioned rules (modulo 109 + 7).

Example
input
Copy
2
2 1
4 3
output
2
2


题意:二叉树要经过a条边,并转b次,有多少种路径。

解题思路:a条路径有a-1个转折点,所以是一个排列组合公式,根节点可以往左往右,所以最后要×2

ans=2*C(b,a-1)

中间涉及到除法的模运算,所以要用乘法逆元。


#include<iostream>
#include<string>
#include<memory.h>
using namespace std;
typedef long long int ll;
const int MOD=1e9+7;

ll f[100005];

ll mpow(ll a, ll b, ll c)
{
    ll ans = 1;
    a = a % c;
    while (b > 0)
    {
        if (b % 2)
            ans = (ans * a) % c;
        b /= 2;
        a = (a * a) % c;
    }
    return ans;
}

//乘法逆元,即将一个除数变为乘数,就是求倒数
ll inv(ll a, ll mod)
{

    return mpow(a,mod-2,mod);//mod是质数才能用
}

int main(){

	f[0]=1;
	for(int i=1;i<=100002;i++)
		f[i]=f[i-1]*i%MOD;
	
	
	int T;
	scanf("%d",&T);
	while(T--){
		ll a,b;
		cin>>a>>b;
		
		ll ans=2*f[a-1]*inv(f[b]*f[a-1-b]%MOD,MOD)%MOD;
		cout<<ans<<endl;
		
	}

	
	return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值