ACM PKU 3318 Matrix Multiplication http://acm.pku.edu.cn/JudgeOnline/problem?id=3318

矩阵乘法的计算这应该是一个比较节省时间的算法了吧,用一个n维数组左乘每个等式两边。改进后时间从O(n^3)变成了O(3*n^2)再加上改成了用C语言的输入函数scanf(),大大减少了输入时间。我的代码:

#include<iostream>
using namespace std;
const int Max=501;
int A[Max][Max]={0},B[Max][Max]={0},C[Max][Max]={0},AA[Max]={0},BB[Max]={0},DD[Max]={0},CC[Max]={0};
int main ()
{
int n;
scanf("%d",&n);
int temp(1);
for (int i=0;i<n;i++)
{
   AA[i]=temp++;
}
for(int i1=0;i1<n;i1++)
    for (int j1=0;j1<n;j1++)
{
     scanf("%d",&A[i1][j1]);
}
for(int i2=0;i2<n;i2++)
    for (int j2=0;j2<n;j2++)
{
     scanf("%d",&B[i2][j2]);
}
for(int i3=0;i3<n;i3++)
    for (int j3=0;j3<n;j3++)
{
     scanf("%d",&C[i3][j3]);
}
for (int ii1=0;ii1<n;ii1++)
   for (int jj1=0;jj1<n;jj1++)
{
   BB[ii1]+=AA[jj1]*A[jj1][ii1]; 
}
for (int ii2=0;ii2<n;ii2++)
   for (int jj2=0;jj2<n;jj2++)
{
   CC[ii2]+=BB[jj2]*B[jj2][ii2]; 
}
for (int ii3=0;ii3<n ;ii3++)
   for (int jj3=0;jj3<n;jj3++)
{
   DD[ii3]+=AA[jj3]*C[jj3][ii3]; 
}
   int pi=0;
   while (pi<n)
   {
    if(DD[pi]!=CC[pi])
    {
     break;      
    } 
    pi++;
   }
   if (pi==n)
    cout<<"YES"<<endl;
   else 
    cout<<"NO"<<endl;
return 0;
}
做得不足的地方是没有调用函数,代码写起来很费劲.

posted on 2011-05-06 19:22  _Clarence  阅读(89)  评论(0编辑  收藏

导航