• [poj 3318] Matrix Multiplication (随机化+矩阵)


    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(n^3) algorithm will get TLE.

    注意:只需要判断是否一样
    如果A*B=C 那么 A*(B*R)=C*R
    用一个随机数组(R)当做矩阵然后再乘即可变为O(n^2)

    code:

    //By Menteur_Hxy
    #include<cstdio>
    #include<iostream>
    #include<algorithm>
    #include<cstring>
    #include<cstdlib>
    #define ll long long
    #define f(a,b,c) for(int a=b;a<=c;a++)
    using namespace std;
    
    inline ll rd() {
        ll x=0,fla=1; char c=' ';
        while(c>'9'|| c<'0') {if(c=='-') fla=-fla; c=getchar();}
        while(c<='9' && c>='0') x=x*10+c-'0',c=getchar();
        return x*fla;
    }
    
    const int MAX=1010;
    const int INF=0x3f3f3f3f;
    int n;
    int a[MAX][MAX],b[MAX][MAX],c[MAX][MAX],ans1[MAX],ans2[MAX],rnd[MAX];
    
    void mul(int a[MAX],int b[MAX][MAX],int c[MAX]) {
        int reg[MAX];
        f(i,1,n) {
            reg[i]=0;
            f(j,1,n) reg[i]+=a[j]*b[j][i];
        }
        f(i,1,n) c[i]=reg[i];
    }
    
    bool jud() {
        f(i,1,n) if(ans1[i]!=ans2[i]) return 0;
        return 1;
    }
    
    int main() {
        f(i,1,MAX) rnd[i]=rand();
        while(scanf("%d",&n)==1) {
            f(i,1,n) f(j,1,n) a[i][j]=rd();
            f(i,1,n) f(j,1,n) b[i][j]=rd();
            f(i,1,n) f(j,1,n) c[i][j]=rd();
            mul(rnd,a,ans1);mul(ans1,b,ans1);mul(rnd,c,ans2);
            if(jud()) printf("YES
    ");
            else printf("NO
    ");
        }
        return 0;
    }
    
    版权声明:本文为博主原创文章,未经博主允许不得转载。 博主:https://www.cnblogs.com/Menteur-Hxy/
  • 相关阅读:
    数据库遇到的2个奇葩的事情
    虚IP解决程序连只读服务器故障漂移
    SQL Server 主库DML操作慢故障处理过程
    优雅地使用pt-archiver进行数据归档(转)
    Mysql表读写、索引等操作的sql语句效率优化问题
    MySQL Performance-Schema(一) 配置篇
    MySQL Performance-Schema(三) 实践篇
    MySQL Performance-Schema(二) 理论篇
    MySQL案例-并行复制乱序提交引起的同步异常
    (转)MySQL- 5.7 sys schema笔记,mysql-schema
  • 原文地址:https://www.cnblogs.com/Menteur-Hxy/p/9247979.html
Copyright © 2020-2023  润新知