http://poj.org/problem?id=3744
Matrix Fast Power:
DP-based recursive
In the case of dp[i] = P*dp[i-1] + (1-p) *dp[i-2]
Since x is very large and up to 100 million, the complexity of this is 100 million.
So here you can use the matrix idea
[Dp[i] dp[i-1]] = [dp[i-1] dp[i-2] | P 1-p|
| 1 0 |
Recursion to get
N-1
[Dp[n] dp[n-1]] = [dp[1] dp[2]] |p 1-p|
| 0 |
Note that I have separated the matrix and determinant here!!!
(because forget the line generation, tangled for four or five days-always thought the last step to do a multiplication)
The title said the first step must go 1 dp[1] = 1
Then take advantage of the fast power (just multiply the matrix with this idea optimization)
11101
The equivalent of all multiplication into binary, 2^0 +2^2 + 2^3 + 2^4
If you have the last 1 then multiply, double the 2 yourself every time.
Is the beginning of the 2^0, and then saw the last 1 total value *2^0 2^0 into 2^1
The penultimate one is 0 total or the original value 2*1 into 2*2
......
To sort a bit
Notice here that when a[i] = = A[i-1] The power is negative, because I'm writing a while (n) so there's going to be a dead loop T------special.
And the final output to. 7f.. WA.
/************************************************* Author:P owatr* Created time:2015-8-31 13:16:26* File Name : B.cpp ************************************************/#include <cstdio> #include <algorithm> #include <iostream> #include <sstream> #include <cstring> #include <cmath> #include <string># Include <vector> #include <queue> #include <deque> #include <stack> #include <list># Include <map> #include <set> #include <bitset> #include <cstdlib> #include <ctime>using namespace std; #define Lson L, Mid, RT << 1#define Rson mid + 1, R, RT << 1 | 1typedef long ll;const int MAXN = 1e5 + 10;const int INF = 0x3f3f3f3f;const int MOD = 1e9 + 7;struct matrix{doubl e A[2][2]; void Inti () {a[0][0] = a[1][1] = 1; A[1][0] = a[0][1] = 0; }}; Matrix Mul (Matrix A, matrix B) {matrix ans; for (int i = 0, i < 2; i++) {for (int j = 0; J < 2; J + +) { ANS.A[I][J] = 0; for (int k = 0; k < 2; k++) {if (a.a[i][k] = = 0 | | b.a[k][j] = = 0) continue; ANS.A[I][J] + = a.a[i][k]*b.a[k][j]; }}} return ans;} Matrix Pow_m (Matrix A, int n) {matrix ans; Ans.inti (); while (n) {if (n&1) ans = mul (ans, a); n >>= 1; A = Mul (A, a); } return ans; Double dp[11];int B[11];int Main () {int n; Double p; Matrix Matrix; Matrix ret; while (~SCANF ("%d%lf", &n, &p)) {Double sum = 1; for (int i = 1; I <= n; i++) scanf ("%d", &b[i]); Sort (b + 1, B + n + 1); Matrix.a[0][0] = p; MATRIX.A[0][1] = 1-p; Matrix.a[1][0] = 1; MATRIX.A[1][1] = 0; ret = pow_m (Matrix, b[1]-1); DP[1] = ret.a[0][0]; Sum *= (1-dp[1]); for (int i = 2; I <= n; i++) {if (b[i] = = B[i-1]) continue; RET = Pow_m(Matrix, B[i]-b[i-1]-1); Dp[i] = ret.a[0][0]; Sum *= (1-dp[i]); } printf ("%.7f\n", sum); } return 0;}
poj3744--probability DP Matrix fast Power optimization--scout YYF I