首页 > 代码库 > Matrix multiplication

Matrix multiplication

题目链接

  • 题意:
    给两个n*n的矩阵,求乘积后对3取摸的结果(1≤n≤800)
  • 分析:
    考虑一下为什么给3呢,对3取摸只可能得到0、1、2,都可以看作两位的,那么在乘法的时候我们可以用分配率将原来的矩阵乘法分成四个矩阵乘法,每个矩阵都只包括0和1。对于0/1矩阵的乘法,可以使用bitset来快速运算
const int MAXN = 801;

bitset<MAXN> r1[MAXN], r2[MAXN], c1[MAXN], c2[MAXN];

int a[MAXN][MAXN];

int main()
{
    int n;
    while (~RI(n))
    {
        REP(i, n) REP(j, n)
        {
            RI(a[i][j]);
            if (a[i][j] >= 3)
                a[i][j] %= 3;
            r1[i][j] = a[i][j] >> 1;
            r2[i][j] = a[i][j] & 1;
        }
        REP(i, n) REP(j, n)
        {
            RI(a[i][j]);
            if (a[i][j] >= 3)
                a[i][j] %= 3;
            c1[j][i] = a[i][j] >> 1;
            c2[j][i] = a[i][j] & 1;
        }
        REP(i, n) REP(j, n)
        {
            a[i][j] = (r1[i] & c1[j]).count() ;
            a[i][j] += ((r1[i] & c2[j]).count()) << 1;
            a[i][j] += ((r2[i] & c1[j]).count()) << 1;
            a[i][j] += (r2[i] & c2[j]).count() ;
            if (a[i][j] >= 3)
                a[i][j] %= 3;
        }
        REP(i, n) REP(j, n)
            printf("%d%c", a[i][j], j == n - 1 ? '\n' : ' ');
    }
    return 0;
}