1 0 1 2 0 1 2 3 4 5 6 7
0 0 1 2 1
#include<cstdio> #include<cstring> #include<algorithm> using namespace std; const int N = 805; int a[N][N], b[N][N], ans[N][N]; void Multi(int n) { int i, j, k, L, *p2; int tmp[N], con; for(i = 0; i < n; ++i) { memset(tmp, 0, sizeof(tmp)); for(k = 0, L = (n & ~15); k < L; ++k) { con = a[i][k]; for(j = 0, p2 = b[k]; j < n; ++j, ++p2) tmp[j] += con * (*p2); if((k & 15) == 15) { for(j = 0; j < n; ++j) tmp[j] %= 3; } } for( ; k < n; ++k) { con = a[i][k]; for(j = 0, p2 = b[k]; j < n; ++j, ++p2) tmp[j] += con * (*p2); } for(j = 0; j < n; ++j) ans[i][j] = tmp[j] % 3; } } int main() { int n, i, j, k; while(~scanf("%d",&n)) { for(i = 0; i < n; i++) for(j = 0; j < n; j++) { scanf("%d",&a[i][j]); a[i][j] %= 3; } for(i = 0; i < n; i++) for(j = 0; j < n; j++) { scanf("%d",&b[i][j]); b[i][j] %= 3; } Multi(n); for(i = 0; i < n; i++) { for(j = 0; j < n-1; j++) printf("%d ", ans[i][j]); printf("%d\n", ans[i][n-1]); } } return 0; }
#include<cstdio> #include<cstring> #include<algorithm> #include<cmath> using namespace std; const int N = 805; int a[N][N], b[N][N], ans[N][N]; int main() { int n, i, j, k; while(~scanf("%d",&n)) { for(i = 1; i <= n; i++) for(j = 1; j <= n; j++) { scanf("%d",&a[i][j]); a[i][j] %= 3; } for(i = 1; i <= n; i++) for(j = 1; j <= n; j++) { scanf("%d",&b[i][j]); b[i][j] %= 3; } memset(ans, 0, sizeof(ans)); for(k = 1; k <= n; k++) //经典算法中这层循环在最内层,放最内层会超时,但是放在最外层或者中间都不会超时,不知道为什么 for(i = 1; i <= n; i++) for(j = 1; j <= n; j++) { ans[i][j] += a[i][k] * b[k][j]; //ans[i][j] %= 3; //如果在这里对3取余,就超时了 } for(i = 1; i <= n; i++) { for(j = 1; j < n; j++) printf("%d ", ans[i][j] % 3); printf("%d\n", ans[i][n] % 3); } } return 0; }
hdu 4920 Matrix multiplication(矩阵相乘)多校训练第5场,布布扣,bubuko.com
hdu 4920 Matrix multiplication(矩阵相乘)多校训练第5场
原文:http://blog.csdn.net/lyhvoyage/article/details/38388897