模拟9 T1
(COGS上也有,链接http://218.28.19.228/cogs/problem/problem.php?pid=1426)
题目描述
f0 = 0,f1 = 1, fn = fn-1 + fn-2(i >= 2),求fn mod p
分析
反正就是矩阵乘法吧,然后快速幂优化。
Fibonacci数列
0 0 1
× 表示递推一次。
1 1 1
这样,递推n次,先计算那个2×2的矩阵的n次幂即可。
1 /************************************************** 2 Origin: Simulation 9 Problem 1 3 Author: Xue Zhonghao 4 Data: 2014-4-9 18:04:48 5 State: Accepted 6 **************************************************/ 7 #include<cstdio> 8 //#include<fstream> 9 //using namespace std; 10 //ifstream fin("eins.in"); 11 //ofstream fout("eins.out"); 12 13 #define LL unsigned long long 14 15 LL P; 16 17 struct matrix { 18 LL ch[2][2]; 19 matrix operator * (matrix A) { 20 matrix B; 21 B.ch[0][0] = (ch[0][0]*A.ch[0][0] + ch[0][1]*A.ch[1][0]) % P; 22 B.ch[0][1] = (ch[0][0]*A.ch[0][1] + ch[0][1]*A.ch[1][1]) % P; 23 B.ch[1][0] = (ch[1][0]*A.ch[0][0] + ch[1][1]*A.ch[1][0]) % P; 24 B.ch[1][1] = (ch[1][0]*A.ch[0][1] + ch[1][1]*A.ch[1][1]) % P; 25 return B; 26 } 27 matrix() { ch[0][0] = 0; ch[0][1] = ch[1][0] = ch[1][1] = 1; } 28 }; 29 30 LL process(int n) { 31 if(n == 0) return 0%P; 32 if(n == 1) return 1%P; 33 matrix a, b; 34 while(!(n & 1)) { 35 n >>= 1; 36 b = b * b; 37 } 38 a = b; 39 while(n >>= 1) { 40 b = b * b; 41 if(n & 1) a = a * b; 42 } 43 return a.ch[0][1]; 44 } 45 46 int main(void) 47 { 48 freopen("eins.in", "r", stdin); 49 freopen("eins.out", "w", stdout); 50 int T, N; 51 LL ans; 52 scanf("%d", &T);//fin>>T; 53 for(int i = 0; i < T; ++i) { 54 scanf("%d%lld", &N, &P);//fin>>N>>P; 55 ans = process(N); 56 printf("%lld\n", ans);//fout<<ans<<endl; 57 } 58 fclose(stdin); 59 fclose(stdout); 60 return 0; 61 }