hdu - 4920 - Matrix multiplication(缓存优化+开挂)
题意:求两个n x n的矩阵相乘后模3的结果,n <= 800。
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4920
——>>呀呀。。
1、3层计算的for进行缓存优化,依据CPU的L1级缓存的实现原理,降低缓存的变更。假设每次都计算完一个单元格的结果再计算下一个单元格的结果。那么被乘矩阵的訪问就会频繁地更新缓存,使效率非常低。。
2、输入开挂,G++提效500ms+。。
3、对乘法进行剪枝。。
没有第1个操作,后果是严重的。。
n^3的复杂度A过,但。此不是正解。。
#include <cstdio>
#include <cstring>
const int MAXN = 800 + 10;
int n;
int A[MAXN][MAXN], B[MAXN][MAXN], mtRet[MAXN][MAXN];
int ReadInt()
{
    int nRet = 0;
    char cIn;
    while ((cIn = getchar()) >= '0' && cIn <= '9')
    {
        nRet = nRet * 10 + cIn - '0';
    }
    return nRet % 3;
}
void Read()
{
    getchar();
    for (int i = 1; i <= n; ++i)
    {
        for (int j = 1; j <= n; ++j)
        {
            A[i][j] = ReadInt();
        }
    }
    for (int i = 1; i <= n; ++i)
    {
        for (int j = 1; j <= n; ++j)
        {
            B[i][j] = ReadInt();
        }
    }
}
void Solve()
{
    memset(mtRet, 0, sizeof(mtRet));
    for (int i = 1; i <= n; ++i)
    {
        for (int k = 1; k <= n; ++k)
        {
            if(!A[i][k]) continue;
            for (int j = 1; j <= n; ++j)
            {
                mtRet[i][j] += A[i][k] * B[k][j];
            }
        }
    }
}
void Print()
{
    for (int i = 1; i <= n; ++i)
    {
        for (int j = 1; j < n; ++j)
        {
            printf("%d ", mtRet[i][j] % 3);
        }
        printf("%d\n", mtRet[i][n] % 3);
    }
}
int main()
{
    while (scanf("%d", &n) == 1)
    {
        Read();
        Solve();
        Print();
    }
    return 0;
}
 
                     
                    
                 
                    
                 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号