题解:P5678 [GZOI2017] 河神

· · 题解

前置知识:

1 快速幂\ 2 位运算\ 3 矩阵乘法

解题思路

首先我们看到题目中的式子。

上面部分的式子比较好理解,我们主要看下面的式子。\ 这里翻译一下:对于所有 0 \le t<K,将 A_{n-k+t} 按位与 b_t 的结果全部 按位或 在一起,最后的结果就是 A_n

所以,看完这个式子后,我们可以考虑修改矩阵乘法的定义,所以我们可以将原来的加法替换为按位或,乘法替换为按位与

根据上面的定义,我们便可以构造出两个初始矩阵,如下:

A = \begin{bmatrix} A_{k-1} & A_{k-2} & \cdots & A_2 & A_1 & A_0 \end{bmatrix} B = \begin{bmatrix} b_{k-1} & -1 & 0 & \cdots & \cdots & 0 \\ b_{k-2} & 0 & -1 & \cdots & \cdots & 0 \\ \vdots & \vdots & \vdots & \ddots & \vdots & \vdots \\ b_0 & 0 & 0 & \cdots & \cdots & 0 \end{bmatrix}

注意:题目中的东西都要开 unsigned long long,且数组下标从 0 开始

最后我们就可以完结撒花了,附代码:

#include<bits/stdc++.h>
using namespace std;
const int N=110;
using ull=unsigned long long;
int n,K;
ull a[N];
ull b[N];
struct M{
    ull c[N][N];
    M(){memset(c,0,sizeof c);}
};

M mul(const M& A,const M& B){//矩阵乘法
    M ans;
    for(int i=0;i<K;i++)
        for(int j=0;j<K;j++)
            for(int k=0;k<K;k++)
                ans.c[i][j]|=(A.c[i][k]&B.c[k][j]);
    return ans;
}

M Mqpow(M A,ull x){//矩阵快速幂
    M L;
    for(int i=0;i<K;i++) L.c[i][0]=b[K-1-i];
    for(int i=1;i<K;i++) L.c[i-1][i]=-1;
    //构造初始矩阵

    while(x){

        if(x&1) A=mul(A,L);
        L=mul(L,L);
        x>>=1;

    }

    return A;
}

int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cin>>n>>K;
    for(int i=0;i<K;i++) cin>>a[i];
    for(int i=0;i<K;i++) cin>>b[i];
    if(n<K){
        cout<<a[n];
        return 0;
    }
    n-=(K-1);
    M S;
    for(int i=0;i<K;i++) S.c[0][i]=a[K-1-i];//构造初始矩阵

    S=Mqpow(S,n);

    cout<<S.c[0][0];

    return 0;
}