P16601 [SYSUCPC 2025] Ecosystem 题解

· · 题解

先考虑只有一个 t 的情况。

设 dp_i 表示总和为 i 的进食序列数,那么有一个朴素的转移:dp_i=\sum_{j=1}^{V} cnt_j\times dp_{i-j}。

其中 V 表示 a_i 的值域,cnt_j 表示消耗 j 份饲料的动物数。

转移矩阵 $M$ 的大小为 $V \times V$。其形式为: $$ M = \begin{bmatrix} cnt_1 & cnt_2 & \cdots & cnt_{V-1} & cnt_V \\ 1 & 0 & \cdots & 0 & 0 \\ 0 & 1 & \cdots & 0 & 0 \\ \vdots & \vdots & \ddots & \vdots & \vdots \\ 0 & 0 & \cdots & 1 & 0 \end{bmatrix} $$ 然后我们就可以 $O(V^3 \log t)$ 转移了,答案就是 $M^t\times dp$,但这还不够,因为我们有 $m$ 个 $t$。 但我们发现一个只有一行的矩阵乘转移矩阵是 $O(V^2)$ 的,并且乘完之后的结果还是一行的矩阵,所以我们预处理一下 $M$ 的 $2^k$ 次方($k$ 最大取到 $64$ 就行),每一次询问的时候用 $2^k$ 凑出 $t$,一开始用 $dp$ 直接去乘就行了,总时间复杂度 $O(mV^2\log t)$。 ``` #include<bits/stdc++.h> #define int long long using namespace std; const int N=105,Mat=100,mod=1e9+7; int n,m; int a[N],mp[N],cnt[N]; int f[N]; struct node{ int a[N][N]; node (){memset(a,0,sizeof a);} int* operator[](int x){return a[x];} void getI(){ for(int i=1;i<=Mat;i++) a[i][i]=1; } node operator*(const node &x)const{ node c; for(int i=1;i<=Mat;i++){ for(int j=1;j<=Mat;j++){ for(int k=1;k<=Mat;k++) c[i][j]=(c[i][j]+a[i][k]*x.a[k][j])%mod; } } return c; } }A,dp,M[65]; node mults(node x,node y){ node res; for(int i=1;i<=Mat;i++){ for(int j=1;j<=Mat;j++){ res[1][i]=(res[1][i]+x[1][j]*y[j][i])%mod; } } return res; } node ksm(node x,int y){ node res; res.getI(); while(y){ if(y&1) res=res*x; y>>=1,x=x*x; } return res; } signed main(){ int maxn=0; scanf("%lld%lld",&n,&m); for(int i=1;i<=n;i++) scanf("%lld",&a[i]),maxn=max(maxn,a[i]),mp[a[i]]++; for(int i=1;i<=maxn;i++) cnt[i]=mp[i]; f[0]=1; for(int i=1;i<=maxn;i++){ for(int j=1;j<=maxn;j++) if(i>=j) f[i]+=(cnt[j]*f[i-j])%mod; } dp[1][1]=1; for(int i=1;i<=maxn;i++) A[1][i]=cnt[i]; for(int i=2;i<=maxn;i++) A[i][i-1]=1; M[0]=A; for(int i=1;i<=64;i++) M[i]=M[i-1]*M[i-1]; while(m--){ int x; scanf("%lld",&x); if(x<=maxn) printf("%lld\n",f[x]); else{ node res=dp; for(int i=0;i<=60;i++) if(x&(1ll<<i)) res=mults(res,M[i]); printf("%lld\n",res[1][1]); } } return 0; } ```