P8989 [北大集训 2021] 随机游走

· · 题解

Description

传送门

Solution

Part 1

根据贪心思想,对于每条加入的边 u \to v,均有 u \in [1,n), v = 1。

记 S(z) 为 m=z 时,某组最优解中,所有加入的边的起点构成的集合(特别的,S(0) = \emptyset)。打表发现:\forall z \ge 1,S_z(z - 1) \subset S_z(z),

记 t_z 为 S(z) - S(z-1) 的唯一元素,考虑 t 有何规律。打表发现,当 n=6 时,t 的前 19 项依次为:5 4 3 2 5 4 3 2 1 5 4 3 2 1 5 4 3 2 1。

规律一目了然:t_1,t_2,\cdots,t_{n-1} 依次为从 n-1 到 2 的所有整数;之后的部分周期为 n-1,每个周期是从 n - 1 到 1 的所有整数。

Part 2

令 c_i 为以 i 为起点的边数,则 c[1,n-1] 可以被划分为 \le 3 段,满足每一段内的元素全部相等。

令 f_i 为从 i 走到终点的期望步数。记答案 x = f_1,则 \forall i \in [2,n],可以递推出 k_i,b_i,满足 f_i = k_ix+b_i,则 x = \frac {-b_n} {k_n}。

由于递推式是线性变换,对于每一段作矩阵快速幂,从而推出 f_n,g_n 即可,时间复杂度 O(\sum \log n)。

Code

注意特判 n=1,并小心模数 \le m 的情况,避免除以 0。

#include <bits/stdc++.h>
#define int long long
using namespace std;

namespace IO{
    inline char nc(){
        static char buf[500001],*p1=buf,*p2=buf;
        return p1==p2&&(p2=(p1=buf)+fread(buf,1,500000,stdin),p1==p2)?EOF:*p1++;
    }
    char out[500001],*pout=out,*eout=out+500000;
    template<typename T> inline T read(){
        char ch=nc(); T sum=0; bool f=false;
        for(;ch<'0'||ch>'9';ch=nc()) if(ch=='-') f=1;
        while(ch>='0'&&ch<='9')sum=sum*10+ch-48,ch=nc();
        return f?-sum:sum;
    }
}
#define read IO::read<int>

int n,m,mod,K,B,trn; vector<pair<int,int>> vec;
struct Matrix{
    int a[2][2];
    Matrix operator * (const Matrix &A) const{
        Matrix res;
        for (int i=0;i<2;i++){
            for (int j=0;j<2;j++)  res.a[i][j]=(a[i][0]*A.a[0][j]+a[i][1]*A.a[1][j])%mod;
        }
        return res;
    }
}M;
inline void Add(int l,int r,int t=1){if(l<=r)vec.emplace_back(l,t),vec.emplace_back(r,-t);}
inline int quick_power(int x,int y){
    int res=1;
    for (;y;y>>=1,(x*=x)%=mod) {if(y&1)(res*=x)%=mod;}
    return res;
}
inline Matrix quick_power(Matrix x,int y){
    Matrix res=x; y--;
    for (;y;y>>=1,x=x*x) {if(y&1)res=res*x;}
    return res;
}
inline int getinv(int x){return quick_power(x,mod-2);}
signed main(){
    int T=read();
    while (T--){
        n=read(),m=read(),mod=read(),vec.clear(),Add(1,n,0),K=1,B=0;
        if (n==1) {puts("0");continue;}
        if (m<n-1)  Add(n-m,n);
        else{
            Add(2,n),m-=n-2;
            Add(1,n,trn=m/(n-1)),m-=trn*(n-1);
            Add(n-m,n);
        }
        sort(vec.begin(),vec.end());
        for (int i=1,s=0,q;i<(int)vec.size();i++){
            int l=vec[i-1].first,r=vec[i].first; (s+=vec[i-1].second)%=mod;
            auto upd=[&](int &var,int x){
                M.a[0][0]=q,M.a[1][0]=mod-x,M.a[1][1]=1;
                M=quick_power(M,r-l),var=(var*M.a[0][0]+M.a[1][0])%mod;
            };
            if (l<r)  q=s+1,upd(K,s),upd(B,q);
        }
        printf("%lld\n",((-B*getinv(K))%mod+mod)%mod);
    }
    return 0;
}