题目:795. 前缀和 - AcWing题库
思路/想法:
输入输出格式有点奇怪,题意没有明确看出来。
代码实现:
// import java.util.*;
// public class Main{
// public static void main(String[] args) {
// Scanner sc = new Scanner(System.in);
// int total = sc.nextInt();
// int m = sc.nextInt();
// int[] arr = new int[total];
// for (int i = 0; i < total; i++) arr[i] = sc.nextInt();
// while (m-- > 0) {
// int a = sc.nextInt() - 1;
// int b = sc.nextInt() - 1;
// int sum = 0;
// while (a <= b) {
// sum += arr[a];
// a++;
// }
// System.out.print(sum);
// System.out.println();
// }
// }
// }
// import java.util.*;
// public class Main{
// public static void main(String[] args) {
// Scanner sc = new Scanner(System.in);
// int m = sc.nextInt();
// int n = sc.nextInt();
// int[] arr1 = new int[m];
// int[] arr2 = new int[m + 1];
// for (int i = 0; i < m; i++) arr1[i] = sc.nextInt();
// for (int i = 1; i <= m; i++) arr2[i] = arr2[i - 1] + arr1[i - 1];
// while (n-- > 0) {
// int a = sc.nextInt();
// int b = sc.nextInt();
// System.out.println(arr2[b] - arr2[a]);
// }
// }
// }
// Exception in thread "main" java.util.InputMismatchException:异常应该是负号的问题,不匹配导致的。
import java.io.*;
class Main{
static int N=100010;
static int[] a=new int[N];
static int[] s=new int[N];
public static void main(String[]args)throws IOException{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
String[]cur=in.readLine().split(" ");
int n=Integer.parseInt(cur[0]);
int m=Integer.parseInt(cur[1]);
String[] arr=in.readLine().split(" ");
for(int i=1;i<=n;i++) a[i]=Integer.parseInt(arr[i-1]);
for(int i=1;i<=n;i++) s[i]=s[i-1]+a[i];
while(m-->0){
String[]q=in.readLine().split(" ");
int l=Integer.parseInt(q[0]);
int r=Integer.parseInt(q[1]);
System.out.println(s[r]-s[l-1]);
}
}
}