CodeForces
来源:互联网 发布:手机淘宝差评怎么删除 编辑:程序博客网 时间:2024/06/03 16:42
题目链接:http://codeforces.com/problemset/problem/226/A
题目大意:一共有三节车厢,rank值小的若想从一节车厢走到另一节车厢,两节车厢内的rank值必须比他小,问所有人都从第三节车厢走到第一节车厢的时间
解题思路:当想移动一个rank小的人,那么比他rank大的人必须在已经在第一节车厢,然后rank小的走到第二节车厢,比他rank大的从第一节车厢走到第三节车厢,rank小的走到第一节车厢,rank大的再从第三节车厢走回第一节,那么可以得出一个递推式,F(n)=F(n-1)*3+2;F(n)表示n个人从第三节车厢移动到第一节车厢所需的时间
AC代码:
解法一:
#include<cstdio>using namespace std;typedef long long LL;int n,Mod;LL quickpow(LL a, LL b){ LL ans = 1; a %= Mod; while (b) { if (b & 1) ans = ans * a % Mod; a = a * a % Mod; b >>= 1; } return ans;}int main(){ scanf("%d%d", &n, &Mod);//F(n)+1=3(F(n-1)+1)构成等比数列 printf("%I64d\n", (quickpow(3, n) - 1 + Mod) % Mod); return 0;}
解法二:
#include<cstdio>#include<iostream>using namespace std;typedef long long LL;const int Max = 10;int Mod;struct Matrix{ int _bulk; LL _matrix[Max][Max]; Matrix(int bulk) :_bulk(bulk) { for (int i = 1;i <= _bulk;++i) for (int j = 1;j <= _bulk;++j) _matrix[i][j] = 0; } Matrix operator*(const Matrix& matrix) { Matrix result(_bulk); for (int i = 1;i <= _bulk;++i) for (int k = 1;k <= _bulk;++k) { if (!_matrix[i][k]) continue; for (int j = 1;j <= _bulk;++j) result._matrix[i][j] += _matrix[i][k] * matrix._matrix[k][j] % Mod; } return result; } void Init() { for (int i = 1;i <= _bulk;++i) _matrix[i][i] = 1; } Matrix quickpow(int n) { Matrix ans(_bulk);ans.Init(); Matrix tmp = (*this); while (n) { if (n & 1) ans = ans*tmp; tmp = tmp*tmp; n >>= 1; } return ans; }};int main(){ int n; scanf("%d%d", &n, &Mod); Matrix matrix(4);//推出矩阵,用矩阵快速幂求解 matrix._matrix[1][1] = 3; matrix._matrix[1][2] = 2; matrix._matrix[2][2] = 1; matrix = matrix.quickpow(n-1); printf("%I64d\n", (matrix._matrix[1][1] * 2 + matrix._matrix[1][2]) % Mod); return 0;}
阅读全文
0 0
- codeforces~~~
- Codeforces
- codeforces
- Codeforces
- codeforces
- codeforces
- Codeforces
- Codeforces
- CodeForces
- CodeForces
- CodeForces
- CodeForces
- CodeForces
- Codeforces
- Codeforces
- Codeforces
- Codeforces
- Codeforces
- BZOJ 2756 [SCOI2012]奇怪的游戏 二分+网络流
- linux中的文件系统类型
- 关于flask-sqlalchemy同字段多条件的过滤方法
- struts2.5 返回json数据 数据截断只有一部分 数据不全问题
- MBR简介
- CodeForces
- 用宏实现数据的交换和找出大的数
- 01背包简介
- git教程
- LINUX:安装jdk1.8
- 手机防尘网
- serialVersionUID的作用
- 饿了么项目---3、vue-router 2.0版本的使用
- Android 在活动中创建菜单(menu)