您的位置:首页 > 产品设计 > 产品经理

PM 3

2015-12-06 17:16 471 查看
C - PM 3

USTC has recently developed the Parallel Matrix Multiplication Machine – PM3, which is used for very large matrix multiplication.

Given two matrices A and B, where A is an N × P matrix and B is a P × M matrix, PM3 can compute matrix C = AB in O(P(N + P + M))
time. However the developers of PM3 soon discovered a small problem: there is a small chance that PM3 makes a mistake, and whenever a mistake occurs, the resultant matrix C will contain exactly one incorrect element.

The developers come up with a natural remedy. After PM3 gives the matrix C, they check and correct it. They think it is a simple task, because there will be at most one incorrect element.

So you are to write a program to check and correct the result computed by PM3.

Input

The first line of the input three integers N, P and M (0 < N, P, M ≤ 1,000), which indicate the dimensions of A and B. Then follow N lines with Pintegers each, giving
the elements of A in row-major order. After that the elements of B and C are given in the same manner.

Elements of A and B are bounded by 1,000 in absolute values which those of C are bounded by 2,000,000,000.

Output

If C contains no incorrect element, print “
Yes
”. Otherwise print “
No
” followed by two more lines, with two integers r and c on the first one, and another integer v on the second one, which indicates
the element of C at row r, column c should be corrected to v.

两个矩阵的乘积得到一个新的矩阵,新的矩阵中可能有一个错误,如果有就输出No,并且输出错误的行和列以及正确的数应该是多少,A*B=C,那么就是A的每行乘以B的每列,【C11+C12=A11*(B11+B21)+A12*(B12+B22)】因此,先把B和C的每行之和分别算出来,用A的第i行中第j个数依次乘以B的第j行之和如果不等于C的第i行之和,则说明错误出现在这一行,然后对C中这行的每个数进行判断,找出错误的列。

#include <iostream>
#include<cstdio>
#include<cstring>
#define NN 1005
using namespace std;
int a[NN][NN],b[NN][NN],c[NN][NN],fc[NN],fb[NN];
int main()
{
int n,p,m;
while(~scanf("%d%d%d",&n,&p,&m))
{
memset(fb,0,sizeof(fb));
memset(fc,0,sizeof(fc));
for(int i=0;i<n;i++)
for(int j=0;j<p;j++)
{
scanf("%d",&a[i][j]);
}
for(int i=0;i<p;i++)
for(int j=0;j<m;j++)
{
scanf("%d",&b[i][j]);
fb[i]+=b[i][j];
}
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
{
scanf("%d",&c[i][j]);
fc[i]+=c[i][j];
}
int x,y,flag=1,sum,ans;
for(int i=0;i<n;i++)
{
sum=0;
for(int j=0;j<p;j++)
{
sum+=a[i][j]*fb[j];
}
if(sum!=fc[i])
{
x=i;
flag=0;
break;
}
}
for(int i=0;i<m;i++)
{
sum=0;
for(int j=0;j<p;j++)
{
sum+=a[x][j]*b[j][i];
}
if(sum!=c[x][i])
{
y=i;
ans=sum;
break;
}
}
if(!flag)
{
printf("No\n");
printf("%d %d\n",++x,++y);
printf("%d\n",ans);
}
else printf("Yes\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: