POJ 3734 Blocks(矩阵快速幂加递推)
Posted FriskyPuppy
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了POJ 3734 Blocks(矩阵快速幂加递推)相关的知识,希望对你有一定的参考价值。
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 6133 | Accepted: 2931 |
Description
Panda has received an assignment of painting a line of blocks. Since Panda is such an intelligent boy, he starts to think of a math problem of painting. Suppose there are N blocks in a line and each block can be paint red, blue, green or yellow. For some myterious reasons, Panda want both the number of red blocks and green blocks to be even numbers. Under such conditions, Panda wants to know the number of different ways to paint these blocks.
Input
The first line of the input contains an integer T(1≤T≤100), the number of test cases. Each of the next T lines contains an integer N(1≤N≤10^9) indicating the number of blocks.
Output
For each test cases, output the number of ways to paint the blocks in a single line. Since the answer may be quite large, you have to module it by 10007.
Sample Input
2 1 2
Sample Output
2 6
题目大意就是给你n个格子, n <= 10^9 , 每个格子可以涂红,蓝, 绿, 黄四种颜色, 但是必须要保证红色和绿色的数量为偶数。 问有几种涂的方案, 答案膜10007
我的第一想法是递推, 但是10^9实在是太大了, 打出一个表大约在6秒左右, 所有这时候就应该想到矩阵快速幂。
首先看状态, 当n == 1时, 很明显只能有两种方案。 这样我们不妨用二维数组dp[n][i] 来表示当前的方案数, N 为格子的数量, 0 <= i <= 3
则dp转移方程就为:
仔细分析就不难看明白转移方程。
#include <iostream> #include <cstdio> #include <algorithm> #include <cstring> using namespace std; typedef long long LL; const int MOD = 10007; struct Matrix { LL a[4][4]; int n, m; void clear() { n = m = 0; memset( a, 0, sizeof(a) ); } Matrix operator * ( const Matrix b ) { Matrix res; res.clear(); res.n = n; res.m = b.m; for( int i = 0; i < n; i++ ) { for( int j = 0; j < b.m; j++ ) { for( int k = 0; k < m; k++ ) { res.a[i][j] += a[i][k] * b.a[k][j]; // printf( "==========\\n" ); } res.a[i][j] %= MOD; } } return res; } }; Matrix quick_power( Matrix a, int n ) { Matrix res; memset( res.a, 0, sizeof(res.a) ); res.clear(); res.n = res.m = 4; for( int i = 0; i < 4; i++ ) { res.a[i][i] = 1; } while( n ) { if( n & 1 ) res = res * a; n >>= 1; a = a * a; } return res; } int main() { int t; scanf( "%d", &t ); Matrix A; A.clear(); A.n = A.m = 4; A.a[0][0] = 2; A.a[0][1] = 1; A.a[0][2] = 1; A.a[0][3] = 0; A.a[1][0] = 1; A.a[1][1] = 2; A.a[1][2] = 0; A.a[1][3] = 1; A.a[2][0] = 1; A.a[2][1] = 0; A.a[2][2] = 2; A.a[2][3] = 1; A.a[3][0] = 0; A.a[3][1] = 1; A.a[3][2] = 1; A.a[3][3] = 2; while( t-- ) { int n; scanf( "%d", &n ); Matrix res = quick_power( A, n ); printf( "%lld\\n", res.a[0][0] ); } return 0; }
这道题很有意义, 果然学计算机还是要学好数学!
以上是关于POJ 3734 Blocks(矩阵快速幂加递推)的主要内容,如果未能解决你的问题,请参考以下文章