poj2440 (matrix fast power)

Click to open the question link


To the effect: The gene whose L position is composed of 0 and 1 cannot contain substrings 101 and 111. Find the number of such genes (L<=10^8)


Ideas: 10^8, decisively fast power. Then excluding 101 and 111, you may use f[i,k] to indicate the number of genes that satisfy the condition, contain i bits in total, and the last three bits are k

Then recursion is carried out according to the k points. For example: f[i,000]=f[i-1,100]+f[i-1,000], f[i,010]=f[i-1,001] (cannot be 101) and so on

Then k has 8 possibilities, f[i,k] has a linear relationship with f[i-1,k'], you can build a fast matrix to do it (8*8 matrix, a bit violent)

Finally, note that there is only one set of data in the sample, but the actual question says there are multiple sets of data.


code show as below:

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);
			}
		}
	}

}


Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326741056&siteId=291194637