zoukankan      html  css  js  c++  java
  • poj3233 Matrix Power Series

    分治即可

    当然也可以把矩阵看成元素用矩阵快速幂做

    #include <iostream>
    #include <cstdio>
    using namespace std;
    int n, k, m;
    struct Matrix{
    	int num[35][35];
    	Matrix operator*(const Matrix &x)const{
    		Matrix re;
    		for(int i=1; i<=n; i++)
    			for(int j=1; j<=n; j++){
    				re.num[i][j] = 0;
    				for(int k=1; k<=n; k++)
    					re.num[i][j] = (re.num[i][j] + num[i][k] * x.num[k][j]) % m;
    			}
    		return re;
    	}
    	Matrix operator+(const Matrix &x)const{
    		Matrix re;
    		for(int i=1; i<=n; i++)
    			for(int j=1; j<=n; j++)
    				re.num[i][j] = (num[i][j] + x.num[i][j]) % m;
    		return re;
    	}
    }a, dan;
    Matrix ksm(Matrix aa, int b){
    	Matrix re=dan;
    	while(b){
    		if(b&1)	re = re * aa;
    		aa = aa * aa;
    		b >>= 1;
    	}
    	return re;
    }
    Matrix sum(int x){
    	if(x==1)	return a;
    	Matrix tmp=sum(x/2);
    	if((x&1)==0)
    		return tmp+tmp*ksm(a, x/2);
    	else
    		return tmp+tmp*ksm(a, x/2)+ksm(a, x);
    }
    
    int main(){
    	cin>>n>>k>>m;
    	for(int i=1; i<=n; i++)
    		for(int j=1; j<=n; j++)
    			if(i==j)	dan.num[i][j] = 1;
    			else	dan.num[i][j] = 0;
    	for(int i=1; i<=n; i++)
    		for(int j=1; j<=n; j++)
    			scanf("%d", &a.num[i][j]);
    	Matrix ans=sum(k);
    	for(int i=1; i<=n; i++){
    		for(int j=1; j<=n; j++)
    			printf("%d ", ans.num[i][j]);
    		printf("
    ");
    	}
    	return 0;
    }
    
  • 相关阅读:
    BZOJ 3529 数表
    BZOJ 3832 Rally
    BZOJ 1086 王室联邦
    BZOJ 2738 矩阵乘法
    2656565
    小L的区间求和
    小L的直线
    Co-prime 杭电4135
    POJ 跳蚤
    B
  • 原文地址:https://www.cnblogs.com/poorpool/p/8551048.html
Copyright © 2011-2022 走看看