跳到正文

题解

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

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

文章信息

发布
2023年10月8日
收录
2026年7月8日
更新
2026年11月10日
篇幅
约 5 分钟
获赞
1
题目
P8989

版本

  1. v1当前

Description

传送门

Solution

Part 1

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

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

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

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

Part 2

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

令 fif_i 为从 ii 走到终点的期望步数。记答案 x=f1x = f_1,则 ∀i∈[2,n]\forall i \in [2,n],可以递推出 ki,bik_i,b_i,满足 fi=kix+bif_i = k_ix+b_i,则 x=−bnknx = \frac {-b_n} {k_n}。

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

Code

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

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