跳到正文

题解

题解:AT_abc129_f [ABC129F] Takahashi's Basics in Education and Learning

Little_Cake_qwq约 3 分钟
原文
文章信息与版本

文章信息

收录
2026年4月7日
更新
2026年4月7日
篇幅
约 3 分钟

版本

  1. v2当前
  2. v1

从 P3216 来的,不知道为啥我卡了好久。。

思路

考虑 DP。设 dpidp_i 为到了等差数列的第 ii 个数对 mm 取余的结果。稍微推一下可得:

dpi=(dpi−1×101+log⁡10si mod m+si) mod mdp_i=(dp_{i-1}\times 10^{1+\log_{10}s_i}\bmod m+s_i)\bmod m

考虑用矩阵优化。设当前矩阵为:

[dpi−1si1]\begin{bmatrix}dp_{i-1}&s_i&1\end{bmatrix}

则有转移矩阵:

[k001100b1]\begin{bmatrix}k&0&0 \\ 1&1&0 \\ 0&b&1\end{bmatrix}

其中 k=1+log⁡10sik=1+\log_{{10}} s_i。

发现 kk 会随着 ii 的变化而变化,考虑枚举 kk,对每一种 kk 来矩阵快速幂即可。

时间复杂度 O(log⁡n)O(\log n),有个 2727 的常数,完全可以通过。

代码

C++
int n,a,b,p;
struct Matrix
{
	int n,m;
	int a[4][4];
	Matrix() { memset(a,0,sizeof(a)); }
	Matrix operator *(const Matrix qwq) const
	{
		Matrix res;
		res.n=n;res.m=qwq.m;
		for(int i=1;i<=res.n;i++)
			for(int j=1;j<=res.m;j++)
				for(int k=1;k<=qwq.n;k++)
					res.a[i][j]=(res.a[i][j]+a[i][k]*qwq.a[k][j]%p)%p;
		return res;
	}
}ans,base;
Matrix qpow(Matrix x,int y)
{
	Matrix res;
	res.n=res.m=x.n;
	for(int i=1;i<=res.n;i++)
		res.a[i][i]=1;
	while(y)
	{
		if(y&1) res=res*x;
		x=x*x;
		y>>=1;
	}
	return res;
}
signed main()
{
	n=read(),a=read(),b=read(),p=read();
	ans.n=1;ans.m=3;
	ans.a[1][1]=0;ans.a[1][2]=a%p;ans.a[1][3]=1;
	for(int pw=10;pw<=1e18;pw*=10)
	{
		base.n=base.m=3;
		base.a[1][1]=pw%p;base.a[3][2]=b%p;
		base.a[2][1]=base.a[2][2]=base.a[3][3]=1;

		if(pw>a)
		{
			int tmp=(pw-a-1)/b+1;
			if(tmp>n) tmp=n;
			n-=tmp;
			if(tmp)
			{
				a+=tmp*b;
				ans=ans*qpow(base,tmp);
			}
		}
	}
	cout<<ans.a[1][1];
	return 0;
}
原文