矩阵乘法优化--poj3318 随机矩阵
来源:互联网 发布:萧航网络 编辑:程序博客网 时间:2024/06/09 14:38
给定矩阵A,B,C,求检验A * B 是否等于C。n = 500
普通矩阵乘法是O(n^3)
但是如果用一个1 * n的矩阵和n * n矩阵相乘只需要O(n^2),所以可以用一个随机矩阵R * A * B ?= R * C
//rand()随机生成[0,RAND_MAX]的数
//如果想要[0,n]内的随机数
//n比RAND_MAX小,取余
//n比RAND_MAX大,1.0 * rand() / RAND_MAX可以得到[0,1]内随机数,再乘以n即可(ps:在n很大时时候会产生锯齿,精度不大)
//1.为什么用int,用long long就过不了?
//2.g++re c++ac?
//!随机矩阵要对n取余!
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <cstring>
using namespacestd;
const int maxn =500 +5;
const int mod =1e9 +7;
class matrix{
public:
int sz;
int m[maxn][maxn];
matrix (int n) {sz = n;init();}
void init(){
memset(m,0,sizeof(m));
for (int i =0; i <sz; i ++) {
m[i][i] =1;
}
}
void input(){
for (int i =0; i <sz; i ++) {
for (int j =0; j <sz; j ++) {
scanf("%d",&m[i][j]);
}
}
}
};
class rand_m{
public:
int sz;
int m[maxn];
rand_m (int n) {sz = n;}
void init_rand(){
int t =rand();
for (int i =0; i <sz; i ++) {
t = rand();
m[i] = t % sz;
}
}
void init(){
memset(m,0,sizeof(m));
}
};
void multiply(rand_m &rd,matrix &a,rand_m &l)
{
for (int i =0; i < rd.sz; i ++) {
int sum =0;
for (int j =0; j < rd.sz; j ++) {
sum = (sum % mod + rd.m[j] * a.m[j][i] %mod) % mod;
}
l.m[i] = sum;
}
}
int main()
{
srand((unsigned)time(0));
int n ;
while (cin >> n) {
matrix a(n),b(n),c(n);
a.input();b.input();c.input();
rand_m rd(n);rd.init_rand();
rand_m l(n),r(n);l.init();r.init();
rand_m tmp(n);tmp.init();
multiply(rd, a,tmp);multiply(tmp, b,l);
multiply(rd, c,r);
bool fg =true;
for (int i =0; i < n; i ++) {
if(l.m[i] != r.m[i]) fg =false;
}
if(fg)printf("YES\n");
elseprintf("NO\n");
}
return0;
}
- 矩阵乘法优化--poj3318 随机矩阵
- POJ3318 Matrix Multiplication ( 随机化 + 矩阵乘法)
- 矩阵乘法的优化
- CUDA 矩阵乘法优化
- 矩阵乘法的优化
- CUDA: 矩阵乘法优化
- 矩阵乘法的优化
- 矩阵乘法优化
- CUDA: 矩阵乘法优化
- 矩阵乘法cache优化
- 矩阵乘法的优化
- 矩阵乘法并行优化
- 矩阵乘法优化算法
- 矩阵乘法优化DP
- 矩阵乘法优化DP
- 矩阵乘法次数优化
- 矩阵乘法优化
- strassen算法优化矩阵乘法
- World final 2012 (Chips Challenge-无源汇最小费用流)
- 通过API文档查询Math类的方法,打印出近似圆,只要给定不同半径,圆的大小随之发生改变
- 日常问题总结(1)
- 你真的了解UIView吗?
- 在Lua中使用自定义类——tolua++工具使用
- 矩阵乘法优化--poj3318 随机矩阵
- onvif soap接口代码框架的关联
- spark之4:编程指南
- 第三节总结
- MondoDB介绍 Python与MongoDB用法,安装PyMongo
- CF346div2-C题(买玩具)
- TCP的连接和断开
- TFS管理不上新加的的项目
- NYOJ 155-求高精度幂