HDOJ Matrix multiplication 4920【矩阵相乘】



Matrix multiplication

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 3594    Accepted Submission(s): 1502


Problem Description
Given two matrices A and B of size n×n, find the product of them.

bobo hates big integers. So you are only asked to find the result modulo 3.
 

Input
The input consists of several tests. For each tests:

The first line contains n (1≤n≤800). Each of the following n lines contain n integers -- the description of the matrix A. The j-th integer in the i-th line equals A ij. The next n lines describe the matrix B in similar format (0≤A ij,B ij≤10 9).
 

Output
For each tests:

Print n lines. Each of them contain n integers -- the matrix A×B in similar format.
 

Sample Input
       
       
       
       
1 0 1 2 0 1 2 3 4 5 6 7
 

Sample Output
       
       
       
       
0 0 1 2 1
 

Author
Xiaoxu Guo (ftiasch)
 

Source
2014 Multi-University Training Contest 5
 

Recommend
We have carefully selected several similar problems for you:   5395  5394  5393  5392  5391 
 


题意:求两个矩阵相乘mod3的结果。


解题思路:注意取余的位置。如果放到相乘的时候取余会超时。记得把A B的初值取余。以及只需在结果取余即可,不要在相乘的时候取余,会超时。

AC代码:

#include <stdio.h>
#include <string.h>
#include <algorithm>

using namespace std;

const int MAXN = 810;
const int Modn = 3;
int N;
int X[MAXN][MAXN];
int Y[MAXN][MAXN];
int t[MAXN][MAXN];

int main()
{
    while(scanf("%d",&N)!=EOF){
        for(int i=0;i<N;i++){
            for(int j=0;j<N;j++){
                scanf("%d",&X[i][j]);
                X[i][j]%=3;
            }
        }
        for(int i=0;i<N;i++){
            for(int j=0;j<N;j++){
                scanf("%d",&Y[i][j]);
                Y[i][j]%=3;
                t[i][j]=0;
            }
        }
        for(int i=0;i<N;i++){
            for(int k=0;k<N;k++)
                if(X[i][k])
                    for(int j=0;j<N;j++)
                        t[i][j]=(t[i][j]+X[i][k]*Y[k][j]%3)%3;
        }
        for(int i=0;i<N;i++){
            printf("%d",t[i][0]);
            for(int j=1;j<N;j++){
                printf(" %d",t[i][j]);
            }
            printf("\n");
        }
    }
    return 0;
}

你可能感兴趣的:(HDOJ Matrix multiplication 4920【矩阵相乘】)