题解 | #矩阵幂#

矩阵幂

https://www.nowcoder.com/practice/31e539ab08f949a8bece2a7503e9319a


import java.util.Arrays;
import java.util.Scanner;

class Matrix {
    public static void mutl(int[][] matrix1, int[][] matrix2) {
        int len = matrix1.length;
        int[][] temp = new int[len][len];
        int[][] temp2 = new int[len][len];
        for (int i = 0; i < len; i++) {
            System.arraycopy(matrix1[i], 0, temp[i], 0, len);
            System.arraycopy(matrix2[i], 0, temp2[i], 0, len);
        }

        int g = 0;
        for (int i = 0; i < len; i++) {
            for (int j = 0; j < len; j++) {
                int sum = 0;
                for (int k = 0; k < len; k++) {
                    sum += temp[i][k] * temp2[k][j];
                }
                matrix1[g / len][g % len] = sum;
                g++;
            }
        }
    }

    public static void add(int[][] m1, int [][]m2) {
        for (int i = 0; i < m1.length; i++) {
            for (int j = 0; j < m1[0].length; j++) {
                m1[i][j] += m2[i][j];
            }
        }
    }

    public static int[][] getE(int n) {
        int[][] ans = new int[n][n];
        for (int i = 0; i < n; i++) {
            ans[i][i] = 1;
        }
        return ans;
    }

    public static int[][] powK(int[][] matrix, int k) {
        int len = matrix.length;
        int [][] ans = getE(len);
        int [][] g = new int[len][len];
        for (int i = 0; i < len; i++) {
            System.arraycopy(matrix[i], 0, g[i], 0, len);
        }
        while (k > 0) {
            if ((k & 1) == 1) {
                Matrix.mutl(ans, g);
            }
            Matrix.mutl(g, g);
            k >>= 1;
        }
        return ans;
    }
}
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            int n = scanner.nextInt();
            int k = scanner.nextInt();
            int[][] matrix = new int[n][n];
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < n; j++) {
                    matrix[i][j] = scanner.nextInt();
                }
            }
            int[][] ans = Matrix.powK(matrix, k);
            for (int i = 0; i < n; i++) {

                for (int j = 0; j < n; j++) {
                    System.out.print(ans[i][j] + " ");
                }
                System.out.println();
            }
        }
    }
}

全部评论

相关推荐

喜欢走神的孤勇者练习时长两年半:爱华,信华,等华,黑华
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务