【题解】P5364 [SNOI2017] 礼物

P5364 SNOI2017 礼物 - 洛谷 (luogu.com.cn)

0.分析

毫无疑问的数学题,设 :第 个朋友带来的礼物数,

对于

不难发现转移式子是固定的,可以往矩阵乘法加速 dp 的方向想。

对于 ,我们发现这类似二项式定理:

由于 ,只要将 也放到矩阵里,就可以加速了。

1.设计

2.代码

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;

typedef long long LL;
const int N = 14;
const LL P = 1000000007; 

LL n; int K;

struct Matrix {
	LL a[N][N];
	Matrix() {
		memset(a, 0, sizeof(a));
	}
};

LL C[N][N];

Matrix operator*(Matrix a, Matrix b) {
	Matrix c;
	for (int i = 0; i <= K + 2; i ++) {
		for (int k = 0; k <= K + 2; k ++) {
			for (int j = 0; j <= K + 2; j ++) {
				c.a[i][j] = (c.a[i][j] + a.a[i][k] * b.a[k][j] % P) % P;
			}
		}
	}
	return c;
}

Matrix q_pow(Matrix a, LL b) {
	Matrix c;
	for (int i = 0; i <= K + 2; i ++) {
		c.a[i][i] = 1;
	}
	while (b) {
		if (b & 1) {
			c = c * a;
		}
		a = a * a;
		b >>= 1;
	}
	return c;
}

void init() {
	memset(C, 0, sizeof(C));
	C[0][0] = 1;
	for (int i = 0; i <= 13; i ++) {
		C[i][0] = C[i][i] = 1;
		for (int j = 1; j < i; j ++) {
			C[i][j] = (C[i - 1][j] + C[i - 1][j - 1]) % P;
		}
	}
}

int main () {
	ios::sync_with_stdio(false);
	cin.tie(0);
	
	cin >> n >> K;
	init();
	
	Matrix m, x, res;
	for (int i = 0; i <= K + 2; i ++) {
		x.a[i][0] = 1;
	}
	
	m.a[0][1] = 1;
	for (int t = 0; t <= K; t ++) {
		m.a[0][2 + t] = C[K][t];
	}
	
	m.a[1][1] = 2;
	for (int t = 0; t <= K; t ++) {
		m.a[1][2 + t] = C[K][t];
	}
	
	for (int j = 0; j <= K; j ++) {
		for (int t = 0; t <= j; t ++) {
			m.a[j + 2][2 + t] = C[j][t];
		}
	}
	
	res = q_pow(m, n - 1) * x;
	
	cout << res.a[0][0] << "\n";
	
	return 0;
}
相关推荐
Tisfy1 小时前
LeetCode 3871.统计范围内的逗号 II:每次算一个逗号
数学·算法·leetcode·题解
无小道1 小时前
C/C++——tuple小记
c++·tuple
小O的算法实验室1 小时前
IEEE TEVC,基于K-means与DQN辅助元启发式算法的多目标两栖无人艇调度模型
算法·kmeans·启发式算法
mmmmath_31 小时前
LeetCode.350.两个数组的交集II
算法
Ivanqhz1 小时前
图是“拓扑 + 类型 + 形状“的世界
算法·决策树·机器学习·php·集成学习
上官唐云2 小时前
2024届本科 | C++ Linux服务端开发求职:从嵌入式到底层服务端的技术之路(附开源项目+简历)
linux·c++·开源·求职招聘
find1star2 小时前
LeetCode 54:螺旋矩阵——用四个边界模拟矩阵收缩
java·算法·leetcode·边缘计算·学习方法
z_mazin2 小时前
逆向一种私有二进制序列化格式:从零到字节级解析器
网络·python·网络协议·算法·rpc
luj_17682 小时前
罚球线右移破防新策略
c语言·开发语言·网络·经验分享·算法