首页 > 试题广场 >

多组_二维数组_T组形式

[编程题]多组_二维数组_T组形式
  • 热度指数:8496 时间限制:C/C++ 3秒,其他语言6秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
给定 t 组询问,每次询问给出一个 nm 列的二维正整数数组 a ,第 i 行第 j 列元素的值为 a_{i,j}
请你分别求出每个数组的元素之和。

输入描述:
第一行有一个整数 t\ (\ 1 \leq t \leq 10^5\ )
随后 t 组数据。
每组的第一行有两个整数 n\ (\ 1 \leq n \leq 10^3\ )m\ (\ 1 \leq m \leq 10^3\ )
每组的随后 n 行,每行有 m 个整数 a_{i,j}\ (\ 1 \leq a_{i,j} \leq 10^9\ )
保证 \sum n \cdot m \leq 10^6


输出描述:
输出 t 行,每行一个整数,代表数组元素之和。
示例1

输入

3
3 4
1 2 3 4
5 6 7 8
9 10 11 12
1 1
2024
3 2
1 1
4 5
1 4

输出

78
2024
16
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        int t = 0;
        if (in.hasNextInt()){
            t = in.nextInt();
        }
        while(0 < t--){
            int n = 0;
            int m = 0;
            if(in.hasNextInt()){
                n = in.nextInt();
            }
            if(in.hasNextInt()){
                m = in.nextInt();
            }
            long sum = 0;
            int count = 0;
            count = n*m;
            while(0<count--){
                if(in.hasNextInt()){
                    sum += in.nextInt();
                }
            }
            System.out.println(sum);
        }
        in.close();
    }
}

发表于 2025-04-05 12:58:25 回复(0)
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        //t组数据
        int t = in.nextInt();
        int i = 0;
        while (i++ < t) {
            //统计组数据
            long sum = 0;
            //每组n行数据
            int n = in.nextInt();
            //每行m个整数
            int m = in.nextInt();
            //sum统计每行数据之和
            int j = 0;
            while (j++ < n) {
                int l = 0;
                while (l++ < m) {
                    sum += in.nextInt();
                }
            }
            System.out.println(sum);
        }
    }
}
发表于 2024-09-26 14:51:19 回复(0)