CF1117D Magic Gems

· · 题解

CF1117D Magic Gems

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

1 \ (i<m) \\ f_{i-m}+f_{i-1} \ (i \ge m) \end{cases}

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

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

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

f_{pm} \\ f_{pm+1} \\ \vdots \\ f_{pm+m-1} \end{bmatrix}

的矩阵(m 为第几行)。

先推一下式子,有:

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

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

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

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

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

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}

写成转移形式就是:

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,m,其转移矩阵共需乘上 \lfloor \frac{n}{m} \rfloor 次,n 对应的答案就是最终答案矩阵的第 n \% m 项,初始答案矩阵为全 1。

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

#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;
}