POJ 3420 Quad Tiling (瓷砖问题+矩阵快速幂)
2016-05-31 16:26
686 查看
题意
用1*2的瓷砖拼成4*n的矩形,求方案数。(n <= 1e9)思路
瓷砖问题还是比较套路的,在数据比较小的时候可以直接把每一行状态压缩一下,然后dfs求出方案。在这样数据比较大的时候我们使用pre和now构造出矩阵,然后用快速幂优化递推n次就可以了。
实际上还有直接手动递推公式的方法,不过需要推导推导的方法可以看这里
代码
#include <stdio.h> #include <string.h> #include <iostream> #include <algorithm> #include <vector> #include <queue> #include <stack> #include <set> #include <map> #include <string> #include <math.h> #include <stdlib.h> #include <time.h> using namespace std; #define LL long long #define lowbit(x) ((x)&(-x)) #define lson l, mid, rt << 1 #define rson mid + 1, r, rt << 1|1 #define MP(a, b) make_pair(a, b) const int INF = 0x3f3f3f3f; const int maxn = 10000 + 7; const double eps = 1e-8; const int MOD = 1000000009; const double PI = acos(-1.0); int n, mod; const int d = 16; struct Matrix { LL a[100][100]; Matrix() { memset(a, 0, sizeof(a)); } void init() { for (int i = 0; i < d; i++) a[i][i] = 1; } Matrix operator * (const Matrix &B)const { Matrix C; for(int i = 0; i < d; i++) for(int j = 0; j < d; j++) for(int k = 0; k < d; k++) C.a[i][j] = (C.a[i][j] + a[i][k] * B.a[k][j]) % mod; return C; } Matrix operator ^ (const int &t)const { Matrix res, A = (*this); res.init(); int p = t; while (p) { if (p & 1) res = res * A; A = A * A; p >>= 1; } return res; } void print() { for (int i = 0; i < d; i++) { for (int j = 0; j < d; j++) printf("%-3d", a[i][j]); printf("\n"); } } }mat; void dfs(int step, int now, int pre) { if (step > 4) return ; if (step == 4) { mat.a[pre][now]++; return ; } dfs(step + 2, (now << 2) | 3, (pre << 2) | 3); dfs(step + 1, (now << 1) | 1, pre << 1); dfs(step + 1, now << 1, (pre << 1) | 1); } int main() { dfs(0, 0, 0); while (scanf("%d%d", &n, &mod) && n) { Matrix res = mat ^ n; printf("%lld\n", res.a[15][15]); } return 0; }
相关文章推荐
- Android最新控件FlexboxLayout
- iOS7 中 boundingRectWithSize:options:attributes:context:计算文本尺寸的使用
- 单例模式
- 模拟并发调用并记录所花费时间
- Matplotlib 教程
- 【CG物理模拟系列】流体模拟--粒子法之SPH(实现)
- 框架整合
- 中兴历年笔试题自己收藏用02
- Middle-题目54:39. Combination Sum
- Linux下的TCP/IP编程----socket的可选项
- ios开发中view.layer.shouldRasterize = YES 的使用说明
- Android OTA升级原理和流程分析
- Dubbo学习过程、使用经验分享及实现原理简单介绍
- 数据库查询优化
- PHP字符串
- ORA-02291: integrity constraint: parent key not found
- 常用正则
- Android基础知识整合篇——广播接收器知识点
- python中的urlencode和urldecode 【中文和url编码转换】
- Ugly Number I and II