|
| 1 | +```java |
| 2 | +import java.io.*; |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +public class Main { |
| 6 | + static int N; |
| 7 | + static long B; |
| 8 | + static int[][] matrix; |
| 9 | + |
| 10 | + public static void main(String[] args) throws IOException { |
| 11 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 12 | + BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); |
| 13 | + StringTokenizer st; |
| 14 | + st = new StringTokenizer(br.readLine()); |
| 15 | + N = Integer.parseInt(st.nextToken()); |
| 16 | + B = Long.parseLong(st.nextToken()); |
| 17 | + matrix = new int[N][N]; |
| 18 | + for (int i = 0; i < N; i++) { |
| 19 | + st = new StringTokenizer(br.readLine()); |
| 20 | + for (int j = 0; j < N; j++) { |
| 21 | + matrix[i][j] = Integer.parseInt(st.nextToken()); |
| 22 | + } |
| 23 | + } |
| 24 | + int[][] result; |
| 25 | + result = pow(matrix, B); |
| 26 | + for (int i = 0; i < N; i++) { |
| 27 | + for (int j = 0; j < N; j++) { |
| 28 | + bw.write(result[i][j] + " "); |
| 29 | + } |
| 30 | + bw.write("\n"); |
| 31 | + } |
| 32 | + bw.close(); |
| 33 | + } |
| 34 | + static public int[][] mul(int[][] a, int[][] b) { |
| 35 | + int[][] c = new int[N][N]; |
| 36 | + for (int i = 0; i < N; i++) { |
| 37 | + for (int j = 0; j < N; j++) { |
| 38 | + for (int k = 0; k < N; k++) { |
| 39 | + c[i][j] = (c[i][j] + (a[i][k] * b[k][j]) % 1000) % 1000; |
| 40 | + } |
| 41 | + } |
| 42 | + } |
| 43 | + return c; |
| 44 | + } |
| 45 | + static public int[][] pow(int[][] a, long n) { |
| 46 | + if(n == 1){ |
| 47 | + int[][] result = new int[N][N]; |
| 48 | + for (int i = 0; i < N; i++) { |
| 49 | + for (int j = 0; j < N; j++) { |
| 50 | + result[i][j] = a[i][j] % 1000; |
| 51 | + } |
| 52 | + } |
| 53 | + return result; |
| 54 | + } |
| 55 | + if(n%2 == 0){ |
| 56 | + return pow(mul(a,a),n/2); |
| 57 | + }else{ |
| 58 | + return mul(pow(mul(a,a),n/2),a); |
| 59 | + } |
| 60 | + } |
| 61 | +} |
| 62 | + |
| 63 | +``` |
0 commit comments