51nod1556 计算(默慈金数)

版权声明:蒟蒻写的文章,能看就行了,同时欢迎大佬们指点错误 https://blog.csdn.net/Algor_pro_king_John/article/details/89784749
Problem

有一个 1 n 1*n 的矩阵,固定第一个数为 1 1 ,其他填正整数, 且相邻数的差不能超过 1 1 ,求方案数。

n 1 0 6 n\le 10^6

Solution

容易发现答案是 f n = f n 1 3 g n f_n=f_{n-1}*3-g_{n}

其中 g i g_i 表示从 ( 0 , 0 ) (0,0) 走到 ( i , 0 ) (i,0) 可以向上,向下向右走一格,但是只能在第一象限的方案数。

然后这个显然可以用 组合数 + 卡特兰数 推一波: i = 1 n 2 ( n 2 i ) C a t a l a n i \sum_{i=1}^{\frac{n}{2}}\binom{n}{2i}Catalan_{i} 但时间复杂度是 O ( n 2 ) O(n^2) 的。

然后去学了一发姿势,发现这个是所谓的默慈金数

一个给定的数 n n 的默慈金数是:

  • 在一个圆上的 n n 个点间,画出彼此不相交的弦的方案数

其中, M ( 1 ) = 1 , M ( 2 ) = 2 M(1)=1,M(2)=2

M ( n + 1 ) = M ( n ) + i = 0 n 1 M ( i ) M ( n 1 i ) M(n+1)=M(n)+\sum_{i=0}^{n-1}M(i)*M(n-1-i)

可以推导出 M ( n + 1 ) = ( 2 n + 3 ) M ( n ) + 3 n M ( n 1 ) n + 3 M(n+1)={{(2n+3)M(n)+3nM(n-1)}\over n+3}

M ( n ) = ( 2 n + 1 ) M ( n 1 ) + ( 3 n 3 ) M ( n 2 ) n + 2 M(n)={{(2n+1)M(n-1)+(3n-3)M(n-2)}\over n+2}

有较好英文水平姿势的同学可以参考推导极其生成函数(反正我是不可能会的),考场上我觉得只要会 O ( n 2 ) O(n^2) 的方法,然后只需知道它是由 n 1 , n 2 n-1,n-2 推到 n n ,找一下规律应该可以。。。

http://mathworld.wolfram.com/MotzkinNumber.html

http://www.docin.com/p1-964777006.html

Code
#include <bits/stdc++.h>

#define F(i,a,b) for (int i = a; i <= b; i ++)

using namespace std;

const int N = 1e6 + 10;
const int Mo = 1e9 + 7;

long long f[N], M[N], n;

int ksm(int x, int y) {
	int ans = 1;
	for (; y ; y >>= 1, x = (1ll * x * x) % Mo)
		if (y & 1)
			ans = (1ll * ans * x) % Mo;
	return ans;
}

int main() {
	scanf("%d", &n);
	
	f[1] = 1, f[2] = 2;
	M[1] = 1, M[2] = 2;
	F(i, 3, n) {
		M[i] = ((2 * i + 1) * M[i - 1] + (3 * i - 3) * M[i - 2]) % Mo * ksm(i + 2, Mo - 2) % Mo;
		f[i] = (f[i - 1] * 3 - M[i - 2]) % Mo;
	}

	printf("%d\n", (f[n] + Mo) % Mo);
}

猜你喜欢

转载自blog.csdn.net/Algor_pro_king_John/article/details/89784749