大意:L位由0和1组成的基因,基因中不能包含子串101以及111,求这样的基因数(L<=10^8)
思路:10^8,果断快速幂。然后不包含101及111,不妨用f[i,k]表示满足条件,共含i位,且末三位为k的基因数
然后按k分情况进行递推。例如:f[i,000]=f[i-1,100]+f[i-1,000],f[i,010]=f[i-1,001](不能是101)等等
然后k有8种可能,f[i,k]与f[i-1,k']有线性关系,就可以构建好矩阵快速幂来做了(8*8的矩阵,有点暴力啊)
最后注意,样例中只有一组数据,但实际题目中说了有多组数据。
代码如下:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class Main {
/**
* @param args
*/
static int n, sum;
static int mat1[][], nowmat[][];
static BufferedReader reader;
static String str;
private static int[][] mulmat(int a[][], int b[][]) {
int c[][] = new int[9][9];
int val;
for (int i = 1; i <= 8; i++)
for (int j = 1; j <= 8; j++) {
val = 0;
for (int k = 1; k <= 8; k++)
val = (val + a[i][k] * b[k][j]) % 2005;
c[i][j] = val;
}
return c;
}
private static int[][] mul(int n) {
if (n == 1)
return mat1;
else {
int mat[][] = mul(n / 2);
mat = mulmat(mat, mat);
if (n % 2 == 1)
mat = mulmat(mat, mat1);
return mat;
}
}
private static void init() {
mat1 = new int[9][9];
mat1[1][1] = 1;
mat1[1][5] = 1;
mat1[2][1] = 1;
mat1[2][5] = 1;
mat1[3][2] = 1;
mat1[4][2] = 1;
mat1[5][3] = 1;
mat1[5][7] = 1;
mat1[7][4] = 1;
}
public static void main(String[] args) throws NumberFormatException,
IOException {
// TODO Auto-generated method stub
reader = new BufferedReader(new InputStreamReader(System.in));
while ((str = reader.readLine()) != null) {
n = Integer.parseInt(str);
if (n == 1)
System.out.println(2);
else if (n == 2)
System.out.println(4);
else if (n == 3)
System.out.println(6);
else {
init();
nowmat = mul(n - 3);
sum = 0;
for (int i = 1; i <= 8; i++)
for (int j = 1; j <= 8; j++)
sum = (sum + nowmat[i][j]) % 2005;
System.out.println(sum);
}
}
}
}