• 51Nod


    51Nod - 1113 矩阵快速幂

    给出一个N * N的矩阵,其中的元素均为正整数。求这个矩阵的M次方。由于M次方的计算结果太大,只需要输出每个元素Mod (10^9 + 7)的结果。
     
    Input
    第1行:2个数N和M,中间用空格分隔。N为矩阵的大小,M为M次方。(2 <= N <= 100, 1 <= M <= 10^9)
    第2 - N + 1行:每行N个数,对应N * N矩阵中的1行。(0 <= N[i] <= 10^9)
    Output
    共N行,每行N个数,对应M次方Mod (10^9 + 7)的结果。
    Input示例
    2 3
    1 1
    1 1
    Output示例
    4 4
    4 4

    题解: 

        快速矩阵幂。

    #include <iostream> 
    #include <vector> 
    #include <cstdio> 
    using namespace std; 
    const int MOD = 1e9 + 7;  
    typedef long long LL; 
    
    int n, m, x; 
    
    vector<vector<LL> > multiple(const vector<vector<LL> > &a, const vector<vector<LL> > &b){
    	vector<vector<LL> > ans(n, vector<LL>(n, 0)); 
    	for(int i=0; i<n; ++i){
    		for(int j=0; j<n; ++j){
    			for(int k=0; k<n; ++k){
    				ans[i][j] += (a[i][k] * b[k][j]) % MOD; 
    				ans[i][j] = ans[i][j] % MOD; 
    			}
    		}
    	}
    	return ans; 
    }
    
    vector<vector<LL> > power_matrix(vector<vector<LL>> t, int num){
    	vector<vector<LL> > ans(n, vector<LL>(n, 0)); 
    	for(int i=0; i<n; ++i){
    		ans[i][i] = 1; 
    	}
    	while(num){
    		if(num%2 == 1){
    			ans = multiple(ans, t); 
    		}
    		t = multiple(t, t); 
    		num = num / 2; 
    	}
    	return ans; 
    }
    
    
    int main(){
    
    	while(scanf("%d %d", &n, &m) != EOF){
    		vector<vector<LL> > t; 
    		for(int i=0; i<n; ++i){
    			vector<LL> tmp; 
    			for(int j=0; j<n; ++j){
    				scanf("%d", &x);
    				tmp.push_back(x);  
    			}
    			t.push_back(tmp); 
    		}
    
    		vector<vector<LL> > ans = power_matrix(t, m); 
    
    		for(int i=0; i<n; ++i){
    			for(int j=0; j<n-1; ++j){
    				printf("%d ", ans[i][j] );
    			}
    			printf("%d
    ", ans[i][n-1] );
    		}
    
    	}
    	return 0; 
    }
    

      

  • 相关阅读:
    php操作zip压缩文件
    php图像处理(thinkphp框架有相对强大的图像处理功能)
    php实现希尔排序(总结)
    PHP glob() 函数详解
    php资源类型变量
    dump var_dump print print_r的区别
    php实现遍历文件目录
    php常用函数
    php全局变量的使用
    php函数按地址传递参数(php引用)
  • 原文地址:https://www.cnblogs.com/zhang-yd/p/6849155.html
Copyright © 2020-2023  润新知