【HDOJ】2157 How many ways??
时间:2014-04-29 11:26:46
收藏:0
阅读:418
矩阵乘法,用DP做各种wa,后来发现原因了。
1 #include <stdio.h> 2 #include <string.h> 3 4 typedef struct { 5 int map[20][20]; 6 } matrix_st; 7 8 matrix_st res, org; 9 int n, m; 10 11 matrix_st multiply(matrix_st a, matrix_st b) { 12 int i, j, k; 13 matrix_st c; 14 15 for (i=0; i<n; ++i) { 16 for (j=0; j<n; ++j) { 17 c.map[i][j] = 0; 18 for (k=0; k<n; ++k) 19 c.map[i][j] += a.map[i][k] * b.map[k][j]; 20 c.map[i][j] %= 1000; 21 } 22 } 23 24 return c; 25 } 26 27 void calc(matrix_st org, int k) { 28 while (k) { 29 if (k & 1) 30 res = multiply(res, org); 31 k >>= 1; 32 org = multiply(org, org); 33 } 34 } 35 36 int main() { 37 int t, i, j, k; 38 39 while (scanf("%d %d", &n, &m)!=EOF && (n||m)) { 40 memset(org.map, 0, sizeof(org.map)); 41 for (i=0; i<m; ++i) { 42 scanf("%d %d", &j, &k); 43 org.map[j][k] = 1; 44 } 45 scanf("%d", &t); 46 while (t--) { 47 memset(res.map, 0, sizeof(res.map)); 48 for (i=0; i<n; ++i) 49 res.map[i][i] = 1; 50 scanf("%d %d %d", &i, &j, &k); 51 calc(org, k); 52 printf("%d\n", res.map[i][j]); 53 } 54 55 } 56 57 return 0; 58 }
评论(0)