hlg2148Resident Evil【矩阵快速幂】
这个矩阵比较好找
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 using namespace std; 5 #define sc scanf 6 #define pr printf 7 #define re return 8 #define me(a, b) memset(a, b, sizeof(a)); 9 #define fr(i, j, k) for(int i = j; i <= k; i++) 10 #define f(i, j, k) for(int i = j; i < k; i++) 11 #define co continue 12 13 const int N = 2; 14 struct Mat { 15 double mat[N][N]; 16 }; 17 18 Mat operator * (Mat a, Mat b) { 19 Mat c; 20 for(int i = 0; i < N; i++) { 21 for(int j = 0; j < N; j++) { 22 c.mat[i][j] = 0; 23 for(int k = 0; k < N; k++) { 24 c.mat[i][j] += a.mat[i][k] * b.mat[k][j]; 25 } 26 } 27 } 28 return c; 29 } 30 31 Mat operator ^ (Mat a, int k) { 32 Mat c; 33 int i, j; 34 for(i = 0; i < N; i++) { 35 for(j = 0; j < N; j++) { 36 c.mat[i][j] = (i == j); 37 } 38 } 39 for(; k; k >>= 1) { 40 if(k & 1) c = c * a; 41 a = a * a; 42 } 43 return c; 44 } 45 46 int main() { 47 double a, b; int n; 48 double p1, p2; int d; 49 Mat m1, m2; 50 while(EOF != sc("%lf %lf %d",&a, &b, &n) ) { 51 m1.mat[0][0] = a; m1.mat[0][1] = b; 52 m1.mat[1][0] = 0; m1.mat[1][1] = 0; 53 fr(i, 1, n) { 54 sc("%lf %lf %d",&p1, &p2, &d); 55 m2.mat[0][0] = 1 - p1; m2.mat[0][1] = p1; 56 m2.mat[1][0] = p2; m2.mat[1][1] = 1 - p2; 57 if(d == 0) { 58 printf("%d\n", (int) (b + 1e-8) ); 59 co; 60 } 61 m2 = m2^d; 62 m2 = m1 * m2; 63 printf("%d\n",(int) ( m2.mat[0][1] + 1e-8) ); 64 } 65 } 66 re 0; 67 }
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <cmath> 5 using namespace std; 6 7 #define sc scanf 8 #define pr printf 9 #define re return 10 #define me(a, b) memset(a, b, sizeof(a)); 11 #define fr(i, j, k) for(int i = j; i <= k; i++) 12 #define f(i, j, k) for(int i = j; i < k; i++) 13 #define co continue 14 15 const int maxn = 1005; 16 17 double st[1][2]; 18 double xx[2][2]; 19 double mid[2][2]; 20 double end[1][2]; 21 22 void xiangcheng(double a[1][2], double b[2][2], double c[1][2]) { 23 f(i, 0, 1) { 24 f(j, 0, 2) { 25 c[i][j] = 0; 26 f(k, 0, 2) { 27 c[i][j] += a[i][k] * b[k][j]; 28 } 29 } 30 } 31 } 32 33 void haha(double a[2][2], double b[2][2], double c[2][2]) { 34 f(i, 0, 2) { 35 f(j, 0, 2) { 36 c[i][j] = 0; 37 f(k, 0, 2) { 38 c[i][j] += a[i][k] * b[k][j]; 39 } 40 } 41 } 42 } 43 44 void jisuan(double a[2][2], int x, double b[2][2]) { 45 if(x == 1) { 46 f(i, 0, 2) { 47 f(j, 0, 2) { 48 b[i][j] = a[i][j]; 49 } 50 } 51 re; 52 } 53 double c[2][2]; 54 if(x % 2 == 1) { 55 jisuan(a, x - 1, c); 56 haha(c, xx, b); 57 } else { 58 jisuan(a, x / 2, c); 59 haha(c, c, b); 60 } 61 } 62 63 int main() { 64 double a, b; int n; 65 double p1, p2; int d; 66 while(EOF != sc("%lf %lf %d",&a, &b, &n) ) { 67 st[0][0] = a; st[0][1] = b; 68 fr(i, 1, n) { 69 sc("%lf %lf %d",&p1, &p2, &d); 70 xx[0][0] = 1 - p1; xx[0][1] = p1; 71 xx[1][0] = p2; xx[1][1] = 1 - p2; 72 if(d == 0) { 73 printf("%d\n", (int) (b + 1e-8) ); 74 co; 75 } 76 jisuan(xx, d, mid); 77 xiangcheng(st, mid, end); 78 printf("%d\n",(int) ( end[0][1] + 1e-8) ); 79 } 80 } 81 re 0; 82 }