Nice Patterns Strike Back
Problem Description
You might have noticed that there is the new fashion among rich people to have their yards tiled with black and white tiles, forming a pattern. The company Broken Tiles is well known as the best tiling company in our region. It provides the widest choices of nice patterns to tile your yard with. The pattern is nice if there is no square of size 2 × 2, such that all tiles in it have the same color. So patterns on the figure 1 are nice, while patterns on the figure 2 are not.
The president of the company wonders whether the variety of nice patterns he can provide to the clients is large enough. Thus he asks you to find out the number of nice patterns that can be used to tile the yard of size N × M . Now he is interested in the long term estimation, so he suggests N ≤ 10100. However, he does not like big numbers, so he asks you to find the answer modulo P .
Input
Output
Sample Input
2 2 5
3 3 23
Sample Output
4
0
Source
import java.awt.Checkbox;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.Scanner; public class Main { static int p; public static class Matrix implements Cloneable {
long[][] a;
int d; public Matrix(int d) {
this.d = d;
a = new long[d][d];
} public Matrix multiply(Matrix m) {
Matrix ret = new Matrix(d);
for (int i = 0; i < d; ++i) {
for (int j = 0; j < d; ++j) {
for (int k = 0; k < d; ++k) {
ret.a[i][j] += a[i][k] * m.a[k][j];
ret.a[i][j] %= p;
}
}
}
return ret;
} public Matrix clone() {
Matrix ret = new Matrix(d);
ret.a = a.clone();
return ret;
} Matrix pow(BigInteger cnt) {
// 先生成一个单位矩阵
Matrix eye = new Matrix(d);
for (int i = 0; i < d; i++)
eye.a[i][i] = 1; for (int i = cnt.bitLength() - 1; i >= 0; i--) {
eye = eye.multiply(eye);
if (cnt.testBit(i)) {
eye = eye.multiply(this);
}
}
return eye;
}
} static boolean check(int x, int y, int m) {
for (int i = 1; i < m; i++) {
if ((x & 3) == (y & 3) && (x & 1) == ((x & 2) >> 1)) {
return false;
}
x >>= 1;
y >>= 1;
} return true;
} public static void main(String[] args) { Scanner cin = new Scanner(new BufferedInputStream(System.in));
PrintWriter cout = new PrintWriter(new BufferedOutputStream(System.out)); int T = cin.nextInt(); while (T-- != 0) {
BigInteger n = cin.nextBigInteger();
int m = cin.nextInt();
p = cin.nextInt(); // 生成矩阵A
int d = (1 << m);
Matrix A = new Matrix(d);
for (int i = 0; i < d; i++)
for (int j = 0; j < d; j++) {
if (check(i, j, m))
A.a[i][j] = 1;
} A = A.pow(n.subtract(BigInteger.ONE)); long ans = 0;
for (int i = 0; i < d; i++)
for (int j = 0; j < d; j++) {
ans = (ans + A.a[i][j]) % p;
} cout.println(ans);
if (T != 0)
cout.println("");
// System.out.println(ans);
} cin.close();
cout.close(); }
}