889. 01 sequence that meets the conditions
①. Title
②. Thinking
-
The problem is directly transformed into a walking grid. If 0 means going to the right and 1 means going up, then the number of 0s in any prefix is not less than 1 and the number is converted to any point on the path, the abscissa is greater than or equal to the vertical coordinate. The number of 0 in all prefixes greater than 1 is below the red line. If the path through the red line is symmetric, then their end points will be mapped to (n−1, n+1), as long as the end point is calculated as (n−1, n+1). 1, n+1) How many paths are there, and then subtracting it from the total is the final answer.
-
Indicates the path from (0,0) to (n,n). The green line and below are legal. If you touch the red line, it is illegal.
-
Algorithm core: every illegal path from (0,0) to (n,n) corresponds to an illegal path from (0,0) to (n-1,n+1)
-
Directly deduced the formula Cn2n−Cn−12n, simplified to Cn2n/(n+1)
③. Learning points
组合计数_卡特兰数
④. Code implementation
import java.util.Scanner;
public class Main {
static int m=(int)1e9+7;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
long res=1;
//直接套用推出来的公式
for (int i = 1,j=2*n; i <=n; i++,j--) {
res=res*j%m; //求2n*(2n-1)*(2n-2)*...*(2n-n+1)
res=res*qmi(i,m-2,m)%m; //快速幂求n的阶乘的逆元
}
System.out.println(res*qmi(n+1,m-2,m)%m); //最后乘上n+1的逆元
}
//快速幂求 a^k%m
static long qmi(long a,long k,long m) {
long res=1;
while(k!=0) {
if((k&1)==1) res=res*a%m;
a=a*a%m;
k>>=1;
}
return res;
}
}