跳到正文

题解

P16601 [SYSUCPC 2025] Ecosystem 题解

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

文章信息

发布
2026年5月24日
收录
2026年5月29日
更新
2026年11月13日
篇幅
约 5 分钟
获赞
8
题目
P16601

版本

  1. v1当前

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

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

其中 VV 表示 aia_i 的值域,cntjcnt_j 表示消耗 jj 份饲料的动物数。

tt 很大,但这个转移比较简单,并且 aia_i 也很小,考虑矩阵加速:

转移矩阵 MM 的大小为 V×VV \times V。其形式为:

M=[cnt1cnt2⋯cntV−1cntV10⋯0001⋯00⋮⋮⋱⋮⋮00⋯10]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(V3log⁡t)O(V^3 \log t) 转移了,答案就是 Mt×dpM^t\times dp,但这还不够,因为我们有 mm 个 tt。

但我们发现一个只有一行的矩阵乘转移矩阵是 O(V2)O(V^2) 的,并且乘完之后的结果还是一行的矩阵,所以我们预处理一下 MM 的 2k2^k 次方(kk 最大取到 6464 就行),每一次询问的时候用 2k2^k 凑出 tt,一开始用 dpdp 直接去乘就行了,总时间复杂度 O(mV2log⁡t)O(mV^2\log t)。

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