跳到正文

题解

CF1117D Magic Gems

oi_tuanzhang约 5 分钟
原文
文章信息与版本

文章信息

发布
2026年8月19日
收录
2026年8月20日
更新
2026年11月11日
篇幅
约 5 分钟
题目
CF1117D

版本

  1. v1当前

CF1117D Magic Gems

记 fif_i 表示填满体积为 ii 有几种填法,考虑新的石头的状态(爆或不爆),有:

fi={1 (i<m)fi−m+fi−1 (i≥m)f_i=\begin{cases} 1 \ (i<m) \\ f_{i-m}+f_{i-1} \ (i \ge m) \end{cases}

先将 n<mn<m 的情况特判掉。

发现第 ii 项只与第 i−mi-m 与 第 i−1i-1 项有关,画个转移图(每行有 mm 的数,以 m=4m=4 为例):

对于图中第 pp(pp 从 00 开始) 行,其上所有数可写成 p×i+qp \times i +q(0≤q≤m−10 \le q \le m-1)的形式,那么考虑维护形如:

[fpmfpm+1⋮fpm+m−1]\begin{bmatrix} f_{pm} \\ f_{pm+1} \\ \vdots \\ f_{pm+m-1} \end{bmatrix}

的矩阵(mm 为第几行)。

先推一下式子,有:

fpm=fpm−1+f(p−1)mf_{pm}= f_{pm-1}+f_{(p-1)m}

fpm+1=fpm+f(p−1)m+1=fpm−1+f(p−1)m+1+f(p−1)m\begin{aligned} f_{pm+1} & =f_{pm}+f_{(p-1)m+1} \\ &=f_{pm-1}+f_{(p-1)m+1}+f_{(p-1)m} \end{aligned}

以此类推,对于 fpm+qf_{pm+q},有:

fpm+q=∑i=0qf(p−1)m+i+fpm−1f_{pm+q}=\sum_{i=0}^{q} f_{(p-1)m+i}+f_{pm-1}

其中 pm−1=(p−1)m+m−1pm-1=(p-1)m+m-1。

由上,则可得出转移矩阵:

[1 0 0 0 ⋯ 11 1 0 0 ⋯ 11 1 1 0 ⋯ 1⋮1 1 1 1 ⋯ 2]\begin{bmatrix} 1\ 0\ 0\ 0\ \cdots \ 1\\ 1\ 1\ 0\ 0\ \cdots \ 1\\ 1\ 1\ 1\ 0\ \cdots \ 1\\ \vdots \\ 1\ 1\ 1\ 1\ \cdots \ 2 \end{bmatrix}

写成转移形式就是:

[fpmfpm+1⋮fpm+m−1]=[1 0 0 0 ⋯ 11 1 0 0 ⋯ 11 1 1 0 ⋯ 1⋮1 1 1 1 ⋯ 2]×[f(p−1)mf(p−1)m+1⋮f(p−1)m+m−1]\begin{bmatrix} f_{pm} \\ f_{pm+1} \\ \vdots \\ f_{pm+m-1} \end{bmatrix}= \begin{bmatrix} 1\ 0\ 0\ 0\ \cdots \ 1\\ 1\ 1\ 0\ 0\ \cdots \ 1\\ 1\ 1\ 1\ 0\ \cdots \ 1\\ \vdots \\ 1\ 1\ 1\ 1\ \cdots \ 2 \end{bmatrix} \times \begin{bmatrix} f_{(p-1)m} \\ f_{(p-1)m+1} \\ \vdots \\ f_{(p-1)m+m-1} \end{bmatrix}

那么对于任意 n,mn,m,其转移矩阵共需乘上 ⌊nm⌋\lfloor \frac{n}{m} \rfloor 次,nn 对应的答案就是最终答案矩阵的第 n%mn \% m 项,初始答案矩阵为全 11。

注意: 所有下标都是从 00 开始的。

C++
#include<bits/stdc++.h>
#define pii pair<int,int>
#define lowbit(x) (x&(-x))
#define int long long
#define inf 1000000000000000000ll
using namespace std;
const int Maxn=1e2+5;
const int Mod=1e9+7;
int n,m;
struct Mat
{
	int n,m;
	int a[Maxn][Maxn];
	Mat()
	{
		memset(a,0,sizeof(a));
	}
}base,f;
Mat operator*(const Mat& p,const Mat& q)
{
	Mat r;
	r.n=p.n,r.m=q.m;
	for(int i=0;i<p.n;i++)
	{
		for(int j=0;j<q.n;j++)
		{
			for(int k=0;k<p.m;k++)
			{
				r.a[i][j]=(r.a[i][j]+p.a[i][k]*q.a[k][j]%Mod)%Mod;
			}
		}
	}
	return r;
}
Mat ksm(Mat a,int b)
{
	Mat base=a,ans;
	ans.n=a.n,ans.m=a.m;
	for(int i=0;i<ans.n;i++) ans.a[i][i]=1;
	while(b)
	{
		if(b&1) ans=ans*base;
		base=base*base;
		b>>=1;
	}
	return ans;
}
signed main()
{
	ios::sync_with_stdio(0);
	cin.tie(0),cout.tie(0);
	cin>>n>>m;
	if(n<m)
	{
		cout<<1<<'\n';
		return 0;
	}
	int p=n/m,q=n%m;
	f.n=m,f.m=1;
	for(int i=0;i<m;i++) f.a[i][0]=1;
	base.n=base.m=m;
	for(int i=0;i<m;i++)
	{
		base.a[i][m-1]++;
		for(int j=0;j<=i;j++)
			base.a[i][j]++;
	}
//	for(int i=0;i<m;i++)
//	{
//		for(int j=0;j<m;j++) cout<<base.a[i][j]<<" ";
//		cout<<'\n';
//	}
	f=ksm(base,p)*f;
//	for(int i=0;i<m;i++) cout<<f.a[i][0]<<'\n';
	cout<<f.a[q][0]<<'\n';
	return 0;
}
原文