题目:
Matrix Multiplication
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 18772 | Accepted: 4035 |
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.
题意很简单,给出三个n阶方阵A,B,C,判断A*B=C是否成立。
由矩阵乘法,我们可以很简单的用O(N^3)的算法计算出这道题。但题目中已明确说明,O(N^3)的算法会TLE,那这时,我们就需要用到随机化算法。
随机化算法,说明白了就是赌博,但获胜概率较大。以此题为例,题目中已明确表示,计算所有点会超时,那么,我们就随机取部分点进行计算。具体实现方法见代码:
由此可以看到,原来O(N^3)的算法,经过随机化的处理,时间复杂度减小了一半。
如果WA了怎么办?答:再提交一次。。。。。
题意很简单,给出三个n阶方阵A,B,C,判断A*B=C是否成立。
由矩阵乘法,我们可以很简单的用O(N^3)的算法计算出这道题。但题目中已明确说明,O(N^3)的算法会TLE,那这时,我们就需要用到随机化算法。
随机化算法,说明白了就是赌博,但获胜概率较大。以此题为例,题目中已明确表示,计算所有点会超时,那么,我们就随机取部分点进行计算。具体实现方法见代码:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <ctime>
using namespace std;
int n;
int matrixA[505][505];
int matrixB[505][505];
int matrixC[505][505];
int main()
{
scanf("%d", &n);
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
scanf("%d",&matrixA[i][j]);
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
scanf("%d",&matrixB[i][j]);
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
scanf("%d",&matrixC[i][j]);
int flag=1;
srand((unsigned)time(NULL)); //随机种子,一定要放在循环外!
for(int i=0;i<100000;i++) //起初设成80000,WA了一发,改成100000,随机次数更多增大可能性
{
int r=rand()%n; //随机行、列
int c=rand()%n;
int sum=0;
for(int j=0;j<n;j++)
{
sum+=matrixA[r][j]*matrixB[j][c];
}
if(sum!=matrixC[r][c])
{
flag=0;
break;
}
}
if(flag)
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
return 0;
}
由此可以看到,原来O(N^3)的算法,经过随机化的处理,时间复杂度减小了一半。
如果WA了怎么办?答:再提交一次。。。。。