P5320 [BJOI2019]勘破神机 题解
SDNetFriend · · 题解
题意这里不再赘述
P5320 [BJOI2019]勘破神机
知识点
数列特征方程,第一类斯特林数,二项式定理,扩展域
做法分析
难度和前面几题完全不是一个级别的。
首先我们先考虑第一种情况,无论哪种情况我们都设
首先可以发现第一种情况的
斐波那契数列通项公式
首先我们假设存在
于是得证,带入得到
推式子求解
因为
然后根据第一类斯特林数
然后带入接着推:
然后为了用二项式定理展开最后的
这里我们设
然后带入原式有:
于是得解。记得把
第二部分
同样推式子,可以发现能凑成几个整列的独立情况有:
-- -- || ---- ------
-- || || |--| |----|
-- || -- |--| |----|(及最后两种上下颠倒以及8,10,12,...列的情况)
然后可以发现完整的列块宽度都是偶数,那么我们设
然后考虑和
然后依旧是解特征方程,得到:
于是像原来那样求解就可以了。
注意
等比数列求和需要判公比为
贴代码
因为定义函数比较多所以封装性应该不错?
#include <bits/stdc++.h>
#define lint long long
using namespace std;
inline lint read(){
char c;lint f=1,res=0;
while(c=getchar(),!isdigit(c))if(c=='-')f=-f;
while(isdigit(c))res=res*10+c-'0',c=getchar();
return res*f;
}
const lint md=998244353;
lint sq;
struct ex{//扩展域
lint a,b;
ex(lint _a=0,lint _b=0)
{a=(_a%md+md)%md;b=(_b%md+md)%md;}
};
inline ex operator+(ex x,ex y)
{return ex(x.a+y.a,x.b+y.b);}
inline ex operator-(ex x,ex y)
{return ex(x.a-y.a,x.b-y.b);}
inline ex operator*(ex x,ex y)
{return ex(x.a*y.a%md+sq*x.b*y.b%md,x.a*y.b%md+x.b*y.a%md);}
inline ex qpow(ex x,lint y){
ex res=ex(1,0);
while(y){
if(y&1)res=res*x;
x=x*x;y>>=1;
}return res;
}
inline ex operator/(ex x,ex y){
ex z=ex(y.a,-y.b);x=x*z;
return x*qpow(y*z,md-2);
}
const int K=605;
ex s[K][K],c[K][K],fac[K],ifac[K];
inline void calc(){//预处理C,S,fac,ifac
s[0][0]=c[0][0]=ex(1,0);
fac[0]=ifac[0]=ex(1,0);
for(int i=1;i<K;++i){
for(int j=1;j<=i;++j)
s[i][j]=s[i-1][j-1]+s[i-1][j]*ex(i-1,0);
c[i][0]=c[i][i]=ex(1,0);
for(int j=1;j<i;++j)
c[i][j]=c[i-1][j-1]+c[i-1][j];
fac[i]=fac[i-1]*ex(i,0);
ifac[i]=qpow(fac[i],md-2);
}
}
ex A,B,x,y;
inline void init(int m){//预设
if(m==2){sq=5;
A=ex(1,0)/ex(0,1);
B=ex(-1,0)/ex(0,1);
x=ex(1,1)/ex(2,0);
y=ex(1,-1)/ex(2,0);
}else{sq=3;
A=ex(3,1)/ex(6,0);
B=ex(3,-1)/ex(6,0);
x=ex(2,1);y=ex(2,-1);
}
}
//函数定义详见题解
inline ex S(int i,int j){return s[i][j];}
inline ex C(int i,int j){return c[i][j];}
inline ex H(ex x,lint l,lint r){
if(x.a==1&&x.b==0)
return ex(r-l+1,0);
ex res=qpow(x,r+1);
res=res-qpow(x,l);
return res/(x-ex(1,0));
}
inline ex G(int j,lint l,lint r){
ex res;
for(int k=0;k<=j;++k){
ex upd=C(j,k)*qpow(A,k)*qpow(B,j-k);
upd=upd*H(qpow(x,k)*qpow(y,j-k),l,r);
res=res+upd;
}return res;
}
inline lint solve(int m,int k,lint l,lint r){
init(m);ex res;
lint _l=l,_r=r;
if(m==2)++l,++r;
else l=(l+1)/2,r/=2;
for(int j=0;j<=k;++j){
ex upd=ex((k-j&1)?-1:1,0);
upd=upd*S(k,j)*G(j,l,r);
res=res+upd;
}
res=res/ex(_r-_l+1,0);
return (res*ifac[k]).a;
}
int T,m;
int main(){
calc();
T=read();m=read();
while(T--){
lint l=read(),r=read();
int k=read();
printf("%lld\n",solve(m,k,l,r));
}
return 0;
}