题目1001:A+B for Matrices(九度 Online Judge)
1,真题
时间限制:1 秒
内存限制:32 兆
特殊判题:否
提交:9896
解决:4030
-
题目描述:
-
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
-
来源:
2011年浙江大学计算机及软件工程研究生机试真题
-
2,分析
- 题目大致意思可以翻译为如下:
- 让矩阵A 和矩阵B相加,判断相加后的矩阵C中,行和列数字全为0的个数。再说得明白点,就是用户先输入要计算的两矩阵行列大小,因为相加,两矩阵行列大小肯定一样。然后依次输入矩阵A和矩阵B的值。输入完成后,自动相加,假设相加结果为矩阵C。先逐行循环统计矩阵C中,是否有一行全为0,若有,则统计数count加1,再逐列循环统计矩阵C中,是否有一行全为0,若有,则统计数count加1,最后输出count的值。
-
3,答案
-
import java.util.Scanner; /** * to test problem_1001 * @author Sunkun * Date: 2013.09.24 */ public class problem_1001{ public static void main(String[] args) { int row = 0; int colum = 0; Scanner input = new Scanner(System.in); // 输入矩阵的行列大小 while(input.hasNext()){ int m = input.nextInt(); if(m <= 0){ break; }else{ row = m; } if(input.hasNext()){ colum = input.nextInt(); } // 给A + B中的A赋值 int[][] a; a = new int[row][colum]; for(int i = 0; i < row; i++){ for(int j = 0; j < colum; j++){ if(input.hasNext()){ a[i][j] = input.nextInt(); } } } // 给A + B中的B赋值 int[][] b; b = new int[row][colum]; for(int i = 0; i < row; i++){ for(int j = 0; j < colum; j++){ if(input.hasNext()){ b[i][j] = input.nextInt(); } } } // 计算 A + B,得到矩阵C, int[][] sum; sum = new int[row][colum]; for(int i = 0; i < row; i++){ for(int j = 0; j < colum; j++){ sum[i][j] = a[i][j] + b[i][j]; } } int count = 0; int i = 0,j = 0; // 统计一行元素是否全为0,若是,则count加1 for(i = 0; i < row; i++){ for(j = 0; j < colum; j++){ if(sum[i][j] != 0){ break; } } if(j == colum){ count++; } } // 统计一列元素是否全为0,若是,则count加1 for(i = 0; i < colum; i++){ for(j = 0; j < row; j++){ if(sum[j][i] != 0){ break; } } if(j == row){ count++; } } // 输出结果 System.out.println(count); } } }
4,备注
- 上述代码直接复制是AC不了的,把类名problem_1001改为Main就可以直接上传通过了:)
-
-