[Luogu P5550] Chino's sequence [matrix multiplication]

Insert picture description here
Insert picture description here


Problem solving ideas

Matrix multiplication

Consider constructing an operation matrix CC [1 2 3 4] \begin{bmatrix} 1&2&3&4\\ \end{bmatrix}[1234]

First, deal with the special cases s and m, if s = 1, m = 2 s=1, m=2s=1m=2
A= [ 0 1 0 0 1 0 0 0 0 0 1 0 0 0 0 1 ] \begin{bmatrix} 0&1&0&0\\ 1&0&0&0\\ 0&0&1&0\\ 0&0&0&1\\ \end{bmatrix} 0100100000100001

When operating numbers, only forward operations

A= [ 1 0 0 0 0 0 0 1 0 1 0 0 0 0 1 1 ] \begin{bmatrix} 1&0&0&0\\ 0&0&0&1\\ 0&1&0&0\\ 0&0&1&1\\ \end{bmatrix} 1000001000010101

Then the problem is converted to CC ∗ A k CC ∗ A^kCCAk


Code

#include<algorithm>
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
using namespace std;
const long long INF=1000000007;
long long n,s,m,k;
struct c{
    
    
	long long n,m;
	long long a[100][100];
}A,B,CC;
c operator *(c A,c B){
    
    
	c C;
	C.n=A.n,C.m=B.m;
	for(int i=1;i<=C.n;i++)
		for(int j=1;j<=C.m;j++)
			C.a[i][j]=0;
	for(int k=1;k<=A.m;k++)
		for(int i=1;i<=C.n;i++)
			for(int j=1;j<=C.m;j++)
				C.a[i][j]=(C.a[i][j]+(A.a[i][k]*B.a[k][j])%INF)%INF;
	return C;
}
void poww(long long x){
    
    
	if(x==1)
	{
    
    
		B=A;
		return;
	}
	poww(x/2);
	B=B*B;
	if(x&1)
		B=B*A; 
}
int main(){
    
    
	scanf("%lld%lld%lld%lld",&n,&s,&m,&k);
	CC.n=1,CC.m=n;
	A.n=n,A.m=n;
	for(int i=1;i<=n;i++)
	{
    
    
		scanf("%lld",&CC.a[1][i]);
		if(i!=s&&i!=m)
		{
    
    
			if(i-1>0)
				A.a[i][i-1]=1;
			else 
				A.a[i][n]=1;
		}
	}		
	if(m-1>0) A.a[s][m-1]=1;
	else A.a[s][n]=1;
	if(s-1>0) A.a[m][s-1]=1;
	else A.a[m][n]=1;
	poww(k);
	CC=CC*B;
	for(int i=1;i<=n;i++)
		printf("%lld ",CC.a[1][i]);
}
/*
4 1 2 3
1 2 3 4
*/

Guess you like

Origin blog.csdn.net/kejin2019/article/details/111402119