void powMatrix(int **C, int **A, int k, int ***powers, char *computed, int N) { int **T, i; T = (int **) malloc(MAX_N * sizeof(int *)); for ( i=0; i<MAX_N; ++i ) T[i] = (int *) malloc(MAX_N * sizeof(int)); if ( (int)computed[k] ) cpyMatrix(C, A, N); else { if ( k==1 ) cpyMatrix(powers[k], A, N); else if ( k%2==0 ) { powMatrix(T, A, k/2, powers, computed, N); mulMatrix(powers[k], T, T, N); } else { powMatrix(T, A, k-1, powers, computed, N); mulMatrix(powers[k], A, T, N); } computed[k] = 1; cpyMatrix(C, powers[k], N); } for ( i=0; i<MAX_N; ++i ) free(T[i]); free(T); }
int64_t solveXorAnd(std::vector<int64_t> &A, std::vector<int64_t> &C, int64_t n, int64_t m) { std::vector<std::vector<int64_t>> AC(n, std::vector<int64_t>(n, 0)); for (int64_t i = 0; i < n; i++) AC[n - 1][i] = C[n - i - 1]; for (int64_t i = 0; i < n - 1; i++) AC[i][i + 1] = -1; std::vector<std::vector<int64_t>> R = powMatrix(AC, m - 1); int64_t res = 0; for (int64_t i = 0; i < n; i++) res ^= R[0][i] & A[i]; return res; }
int main() { int N, K, i, j, k; int **A; int **S; int **T; int ***powers; char *computed; A = (int **) malloc(MAX_N * sizeof(int *)); for ( i=0; i<MAX_N; ++i ) A[i] = (int *) malloc(MAX_N * sizeof(int)); S = (int **) malloc(MAX_N * sizeof(int *)); for ( i=0; i<MAX_N; ++i ) S[i] = (int *) malloc(MAX_N * sizeof(int)); T = (int **) malloc(MAX_N * sizeof(int *)); for ( i=0; i<MAX_N; ++i ) T[i] = (int *) malloc(MAX_N * sizeof(int)); powers = (int ***) malloc((MAX_K+1) * sizeof(int **)); for ( i=0; i<MAX_K+1; ++i ) { powers[i] = (int **) malloc((MAX_N) * sizeof(int *)); for ( j=0; j<MAX_N; ++j ) { powers[i][j] = (int *) malloc((MAX_N) * sizeof(int)); } } computed = (char *) malloc((MAX_K+1) * sizeof(char)); while ( ~scanf("%d %d", &N, &K) && N!=0 ) { readMatrix(A, N); for ( k=1; k<=K; ++k ) computed[k] = 0; for ( i=0; i<N; ++i ) for ( j=0; j<N; ++j ) S[i][j] = 0; for ( k=1; k<=K; ++k ) { powMatrix(T, A, k, powers, computed, N); addMatrix(S, S, T, N); } printMatrix(S, N); } }