zoukankan      html  css  js  c++  java
  • 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; 
    }
    

      

  • 相关阅读:
    SQL盲注攻击的简单介绍
    xss编码小结
    XssEncode
    xss payload
    2014年八大信息安全峰会演讲
    xss bypass
    移动APP安全在渗透测试中的应用
    WAF实现扫描器识别
    thinkphp的系统变量
    thinkphp AOP(面向切面编程)钩子和行为
  • 原文地址:https://www.cnblogs.com/zhang-yd/p/6849155.html
Copyright © 2011-2022 走看看