1. 程式人生 > >51Nod - 1113 矩陣快速冪

51Nod - 1113 矩陣快速冪

return ios brush tdi 需要 can vector 元素 turn

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\n", ans[i][n-1] );
		}

	}
	return 0; 
}

  

51Nod - 1113 矩陣快速冪