zoukankan      html  css  js  c++  java
  • Poj 3318 Matrix Multiplication( 矩阵压缩)

    Matrix Multiplication
    Time Limit: 2000MS   Memory Limit: 65536K
    Total Submissions: 18928   Accepted: 4074

    Description

    You are given three n × n matrices A, B and C. Does the equation A × B = C hold true?

    Input

    The first line of input contains a positive integer n (n ≤ 500) followed by the the three matrices A, B and C respectively. Each matrix's description is a block of n × n integers.

    It guarantees that the elements of A and B are less than 100 in absolute value and elements of C are less than 10,000,000 in absolute value.

    Output

    Output "YES" if the equation holds true, otherwise "NO".

    Sample Input

    2
    1 0
    2 3
    5 1
    0 8
    5 1
    10 26
    

    Sample Output

    YES

    Hint

    Multiple inputs will be tested. So O(n3) algorithm will get TLE.

    Source

     
    /*
    题意:有3个n*n的矩阵A,B,C,问AB是否等于C。
    思路:题目描述很简单,就是用矩阵乘法,但是很明显矩阵乘法的时间复杂度为O(n^3),很明显超时。那怎么改进呢?就是用压缩矩阵的方法:
    设矩阵R是1*n的矩阵,根据矩阵的性质,若R*A*B=R*C,那么A*B=C。由此可以看出来,虽然多成了一个矩阵,但是时间复杂度成了O(n^2)。那么问题是这个R的行列式该怎么设定,有人用的随机算法,但是随机算法可能在关键点上出现错误,可以将R设定成一个递增的数列{1,2,3……}。
    */
    #include<iostream>
    #include<vector>
    #include<stdio.h>
    #include<string.h>
    using namespace std;
    int n,x;
    int a[505][505],b[505][505],c[505][505];
    bool work()
    {
        int R[505],ra[505],rab[505],rc[505];
        for(int i=1;i<=n;i++) {R[i]=i; ra[i]=0; rab[i]=0; rc[i]=0;}
    
        for(int j=1;j<=n;j++)
            for(int i=1;i<=n;i++)
              ra[j]+=R[i]*a[i][j];
    
         for(int j=1;j<=n;j++)
            for(int i=1;i<=n;i++)
              rab[j]+=ra[i]*b[i][j];
    
         for(int j=1;j<=n;j++)
            for(int i=1;i<=n;i++)
              rc[j]+=R[i]*c[i][j];
    
         for(int i=1;i<=n;i++)
            if (rab[i]!=rc[i]) return 0;
        return 1;
    }
    int main()
    {
        scanf("%d",&n);
        for(int i=1;i<=n;i++)
             for(int j=1;j<=n;j++)
               scanf("%d",&a[i][j]);
        for(int i=1;i<=n;i++)
            for(int j=1;j<=n;j++)
                scanf("%d",&b[i][j]);
        for(int i=1;i<=n;i++)
            for(int j=1;j<=n;j++)
                scanf("%d",&c[i][j]);
        if (work()) printf("YES
    ");
          else printf("NO
    ");
        return 0;
    }
  • 相关阅读:
    进入正在运行的Docker的asp.net core容器
    EF 更新记录发现外键更改但更新又跳回以前值
    远程获取http数据和提交数据
    C# 32位16进制加密
    netcore命令行运行程序
    MD5加密32位16进制
    C# MD5加密32位16进制有时少一位问题
    netcoreMVC中使用Vue模板分页封装(不适合数据量大)
    Vue组件间传值 和 访问
    jenkins部署安装
  • 原文地址:https://www.cnblogs.com/stepping/p/7146230.html
Copyright © 2011-2022 走看看