BZOJ2396 神奇的矩阵 【随机化 + 矩乘】

题目链接

BZOJ2396

题解

一种快速判断两个矩阵是否相等的方法:
对于两个\(n * n\)矩阵,两边同时乘一个\(n * 1\)的随机矩阵,如果结果相等,那么有很大概率两个矩阵相等

如果左边是\(A * B\)的话,用矩阵的结合律先让\(B\)乘就好了,这样子总是一个\(n * n\)的矩阵乘一个\(n * 1\)的矩阵
复杂度\(O(n^2)\)

#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#define LL long long int
#define Redge(u) for (int k = h[u],to; k; k = ed[k].nxt)
#define REP(i,n) for (int i = 1; i <= (n); i++)
#define BUG(s,n) for (int i = 1; i <= (n); i++) cout<<s[i]<<' '; puts("");
using namespace std;
const int maxn = 1005,maxm = 100005,INF = 1000000000;
inline int read(){
	int out = 0,flag = 1; char c = getchar();
	while (c < 48 || c > 57){if (c == '-') flag = -1; c = getchar();}
	while (c >= 48 && c <= 57){out = (out << 3) + (out << 1) + c - 48; c = getchar();}
	return out * flag;
}
int a[maxn][maxn],b[maxn][maxn],c[maxn][maxn],d[maxn];
int s[maxn],t1[maxn],t2[maxn],n,flag;
void mul(int a[][maxn],int b[maxn],int s[maxn]){
	REP(i,n){
		s[i] = 0;
		REP(j,n) s[i] += a[i][j] * b[j];
	}
}
int main(){
	while (~scanf("%d",&n)){
		flag = true;
		REP(i,n) REP(j,n) a[i][j] = read();
		REP(i,n) REP(j,n) b[i][j] = read();
		REP(i,n) REP(j,n) c[i][j] = read();
		REP(i,n) d[i] = rand();
		mul(b,d,s);
		mul(a,s,t1);
		mul(c,d,t2);
		REP(i,n) if (t1[i] != t2[i]) {puts("No"); flag = false; break;}
		if (flag) puts("Yes");
	}
	return 0;
}

posted @ 2018-05-04 10:16  Mychael  阅读(272)  评论(0编辑  收藏  举报