zoj 2317 Nice Patterns Strike Back(矩陣乘法)
阿新 • • 發佈:2017-06-16
scanner article value charat name amp -s ann zju
problemId=1317">http://acm.zju.edu.cn/onlinejudge/showProblem.do? problemId=1317
給出一個n*m的矩陣(n <= 10^100, m <= 5),對於2*2的子方格若全是黑色或全是白色的是非法的,用黑白兩色去染n*m的方格,問共同擁有多少種合法的染色方案。
構造出轉移矩陣,上一行向下一行的轉移矩陣。由於m<=5,每行最多有32個狀態。能夠進行狀態壓縮構造出一個32*32的轉移矩陣A。A[i][j] = 1表示上一行i狀態能夠向下一行的j狀態轉移。否則不能轉移。要求最後的合法方案數,就再構造一個B矩陣,是一個32*1的矩陣,表示了到達第一行每個狀態的方案數。那麽A*B就表示到達第二行每個狀態的方案數。以此類推。A^n-1 * B表示到達第n行每個狀態的合法方案數,那麽全部狀態相應方案數的和就是總的方案數。
由於n特別大。要用到大數。我存矩陣的時候開始定義的大數類,一直T。改成了int型才A,1s+,難道大數類這麽慢麽,5s都過不了。
import java.io.*; import java.math.BigInteger; import java.util.Scanner; class Matrix { public int [][] mat = new int[35][35]; public Matrix() { } public void init() { for(int i = 0; i < 35; i++) { for(int j = 0; j < 35; j++) { if(i == j) mat[i][j] = 1; else mat[i][j] = 0; } } } } public class Main { public static Matrix A,B,res; public static BigInteger n; public static int m,p,test,mm; static Scanner cin = new Scanner(System.in); public static void buildA() { for(int i = 0; i < mm; i++) { for(int j = 0; j < mm; j++) { String s1 = Integer.toBinaryString(i); String s2 = Integer.toBinaryString(j); String ss1 = new String(); String ss2 = new String(); for(int k = 0; k < m-s1.length(); k++) ss1 += '0'; ss1 += s1; for(int k = 0; k < m-s2.length(); k++) ss2 += '0'; ss2 += s2; int flag = 0; for(int k = 0; k < m-1; k++) { if(ss1.charAt(k)-'0' == 0 && ss1.charAt(k+1)-'0' == 0 && ss2.charAt(k)-'0' == 0 && ss2.charAt(k+1)-'0' == 0) {flag = 1;break;} if(ss1.charAt(k)-'0' == 1 && ss1.charAt(k+1)-'0' == 1 && ss2.charAt(k)-'0' == 1 && ss2.charAt(k+1)-'0' == 1) {flag = 1;break;} } if(flag == 1) A.mat[i][j] = 0; else A.mat[i][j] = 1; } } } public static Matrix Mul(Matrix x,Matrix y) { Matrix ans = new Matrix(); for(int i = 0; i < mm; i++) { for(int k = 0; k < mm; k++) { if(x.mat[i][k] == 0) continue; for(int j = 0; j < mm; j++) { ans.mat[i][j] = (ans.mat[i][j]+x.mat[i][k]*y.mat[k][j])%p; } } } return ans; } public static Matrix Pow(Matrix tmp,BigInteger nn) { Matrix ans = new Matrix(); ans.init(); while(nn.compareTo(BigInteger.ZERO) > 0) { if( nn.remainder(BigInteger.valueOf(2)).compareTo(BigInteger.ONE) == 0) ans = Mul(ans,tmp); nn = nn.divide(BigInteger.valueOf(2)); tmp = Mul(tmp,tmp); } return ans; } public static void main(String[] args) throws IOException { int test = cin.nextInt(); while((test--) > 0) { n = cin.nextBigInteger(); m = cin.nextInt(); p = cin.nextInt(); mm = (1<<m); A = new Matrix(); B = new Matrix(); buildA(); for(int i = 0; i < mm; i++) B.mat[i][0] = 1; res = Pow(A,n.subtract(BigInteger.ONE)); res = Mul(res,B); int anw = 0; for(int i = 0; i < mm; i++) { anw = (anw+res.mat[i][0])%p; } System.out.println(anw); if(test > 0) System.out.println(); } } }
zoj 2317 Nice Patterns Strike Back(矩陣乘法)