1. 程式人生 > >A+B for Matrices

A+B for Matrices

1.題目描述

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, ea

輸出
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


2.分析

這道題目好像是浙江大學研究生複試上機題的題目。
剛開始讀題目,看不懂,很是尷尬,嘗試過用百度翻譯和有道翻譯去翻譯

這些個翻譯真的水,根本沒get到題目意思,這道題目大概意思是輸入兩個數M,N為矩陣的行,列,然後將A,B兩個矩陣相加後,(相加後)的行列中的每一行為0則+1,每一列為0則加1.
舉例子把
樣例:2 3(輸入2行三列的矩陣)
1 2 3
4 5 6 (這兩行輸入實際是輸入矩陣A的)
-1 -2 -3
-4 -5 -6(這兩行輸入實際是輸入矩陣B的)
2的M次方就是4,就是四行的意思,不是翻譯說的那啥。
然後將A,B矩陣相加為
0 0 0
0 0 0
第一行,第二行的元素都為0,+2
第一列,第二列,第三列的元素都為0,+3
所以輸出5.
題目意思是這個樣子


3.原始碼參考

#include <iostream>
using namespace std;

int A[10][10];
int B[10][10];
int AB[10][10]; //儲存A矩陣+B矩陣的和的矩陣 

int main()
{
    int m,n;

    while(cin >> m && m != 0){
        cin >> n;
        int count = 0;//記錄行、列為0的總數

        //輸入矩陣A 
        for(int i = 0;i < m;i++){
            for(int j = 0;j < n;j++){
                cin >> A[i][j];
            }
        }
        //輸入舉證B,再進行相加的結果存到矩陣AB 
        for(int i = 0;i < m;i++){
            for(int j = 0;j < n;j++){
                cin >> B[i][j];
                AB[i][j] = A[i][j] + B[i][j];
            }
        }

        //這裡我們判斷每一行是否都為0,如果是flag為真,count++,否則不成立 
        for(int i = 0;i < m;i++){
            int flag = 1;
            for(int j = 0;j < n;j++){
                if(AB[i][j] != 0){
                    flag = 0;
                    break;
                }
            }
            if(flag){
                count++;
            }
        }

        //這裡我們判斷每一列是否都為0,如果是flag為真,count++,否則不成立
        for(int j = 0;j < n;j++){
            int flag = 1;
            for(int i = 0;i < m;i++){
                if(AB[i][j] != 0){
                    flag = 0;
                    break;
                }
            }
            if(flag){
                count++;
            }
        }
        cout << count << endl;
    }
    return 0;
}

如果英語沒點書,還是恐怖啊浙大!