zoukankan      html  css  js  c++  java
  • [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/
  • 相关阅读:
    Http record java
    Java String constructed from byte array has bad length
    Schema
    Scale-up(纵向扩展) vs Scale-out(横向扩展)
    数据同步
    JDBC and Oracle conn.commit and conn.setAutocommit not working properly
    DGIM
    Github Blog 搭建手册
    软件探索(一)
    经典书单 —— 人文社科
  • 原文地址:https://www.cnblogs.com/Menteur-Hxy/p/9247979.html
Copyright © 2011-2022 走看看