POJ 3744 矩阵快速幂

思路:

http://poj.org/problem?id=3744

主要涉及的方面:

快速幂和fibonacci的运用

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <algorithm>
 4 using namespace std;
 5 
 6 const int num = 2;
 7 struct mat
 8 {
 9     double m[num][num];
10 };
11 
12 mat I{
13     1,0,
14     0,1
15 };
16 
17 mat mul(mat a, mat b) {
18     mat ans;
19     for(int i=0;i<num;i++)
20         for (int j = 0; j < num; j++) {
21             ans.m[i][j] = 0;
22             for (int k = 0; k < num; k++)
23                 ans.m[i][j] += a.m[i][k] * b.m[k][j];
24         }
25     return ans;
26 }
27 
28 mat quick_pow(mat a, int n) {
29     mat ans = I; 
30     mat temp = a;
31     while (n) {
32         if (n & 1)
33             ans = mul(ans, temp);
34         temp = mul(temp, temp);
35         n >>= 1;
36     }
37     return ans;
38 }
39 
40 int main()
41 {
42     int n, x[40];
43     double p;
44     while (cin >> n >> p) {
45         for (int i = 0; i < n; i++)
46             cin >> x[i];
47         sort(x, x + n);
48 
49         double ans = 1;
50         mat tt{
51             p,1 - p,
52             1,0
53         };
54         mat temp;
55         temp= quick_pow(tt, x[0] - 1);
56         ans *= (1 - temp.m[0][0]);
57 
58         for (int i = 1; i < n; i++)
59         {
60             if (x[i] == x[i - 1])
61                 continue;
62             temp = quick_pow(tt, x[i]-x[i-1] - 1);
63             ans *= (1 - temp.m[0][0]);
64         }
65         printf("%.7f\n", ans);
66     }
67     return 0;
68 }

 

posted on 2016-10-20 21:02  mkfoy  阅读(141)  评论(0)    收藏  举报

导航