-
题目描述:
-
This time, you are supposed to find A+B where A and B are two matrices, and then count the number of zero rows and columns.
-
输入:
-
The input consists of several test cases, each starts with a pair of positive integers M and N (≤10) which are the number of rows and columns of the matrices, respectively. Then 2*M lines follow, each contains N integers in [-100, 100], separated by a space. The first M lines correspond to the elements of A and the second M lines to that of B.
The input is terminated by a zero M and that case must NOT be processed.
-
输出:
-
For each test case you should output in one line the total number of zero rows and columns of A+B.
-
样例输入:
-
2 2 1 1 1 1 -1 -1 10 9 2 3 1 2 3 4 5 6 -1 -2 -3 -4 -5 -6 0
-
样例输出:
-
1
5
-
题目大意是:先输入矩阵的行数和列数,然后依次输入这两个矩阵,输出为这两个矩阵之和的 整行或整列为0的总数。
-
思路如下:
-
对于矩阵,一般我们可以用二维数组来表示,通过两层循环完成赋值;
-
先得到两个矩阵之和,然后统计其整行或整列为0的总数;
-
第一次写的代码如下(错误的):
-
#include<iostream> #include<vector> using namespace std; int main() { int m,n; int sum,total; vector<int> v; while(true) { cin>>m; if(m==0) break; cin>>n; total = 0; int arr_a[9][9],arr_b[9][9],arr_c[9][9]; for(int i=0;i<m;i++) for(int j=0;j<n;j++) cin>>arr_a[i][j]; for(int i=0;i<m;i++) for(int j=0;j<n;j++) cin>>arr_b[i][j]; for(int i=0;i<m;i++) for(int j=0;j<n;j++) arr_c[i][j] = arr_a[i][j]+arr_b[i][j]; for(int i=0;i<m;i++) { sum = 0; for(int j=0;j<n;j++) sum += arr_c[i][j]; if(sum==0) total++; } for(int i=0;i<n;i++) { sum = 0; for(int j=0;j<m;j++) sum += arr_c[j][i]; if(sum==0) total++; } v.push_back(total); } for(int i=0;i<v.size();i++) cout<<v[i]<<endl; return 0; }
-
这里需要注意的是,当输入矩阵的行数为0后,程序就退出,因此需要先判断m的值,再输入n。
-
(关于输出,到底是每输完一组就输出结果还是全部输完再输出结果,题目中没有做明确表示。在OJ上测试两种方式均能通过,不过,这里还是根据给出的样例,按全部输完再输出结果这种方式来做。)
-
上面的代码比较好理解:
-
先输入矩阵A,并将其保存在arr_a中;再输入矩阵B,并将其保存在arr_b中;再将矩阵A、B相加得到矩阵C,并将其保存在arr_c中。
-
然后对于C的每一行与每一列,计算其和,统计和为0的数目。
-
上面的代码有一些错误以及改进之处:
-
首先,数组长度设置错误,应为
-
注意中括号里的数值是元素个数或者说长度,而不是最后一个元素的索引。int arr_a[10][10],arr_b[10][10],arr_c[10][10];
-
然后,统计C的整行或整列为0的数目的方法错了,例如:
-
输入为:
-
-
2 2 1 1 1 1 0 -2 -2 0
-
按照上面的程序的意思,结果应该是4,显然是错误的。
-
那么,正确的统计方式应该是怎样的?
-
然后,考虑优化。
-
定义三个数组真的有必要?程序的写法能否再精炼些?
-
修改后的代码如下:
-
#include<iostream> #include<vector> using namespace std; int main() { int i,j,m,n,tmp; vector<int> v; while(cin>>m, m) { cin>>n; int arr[10][10]; for(i=0;i<m;i++) for(j=0;j<n;j++) cin>>arr[i][j]; for(i=0;i<m;i++) for(j=0;j<n;j++) arr[i][j] += (cin>>tmp, tmp); tmp = 0; for(i=0;i<m;i++) { for(j=0;j<n;j++) if(arr[i][j] != 0) break; if(j==n) tmp++; } for(i=0;i<n;i++) { for(j=0;j<m;j++) if(arr[j][i] != 0) break; if(j==m) tmp++; } v.push_back(tmp); } for(i=0;i<v.size();i++) cout<<v[i]<<endl; return 0; }
-