1 | 2 | 3 | 4 | 5 | |
---|---|---|---|---|---|
배열 a | 5 | 4 | 3 | 2 | 1 |
배열 b | 5 | 9 | 12 | 14 | 15 |
예제 입력에서 1,3이면, b[3]-b[0] = 12이고,
2,4이면 b[4]-b[1] = 9
5,5이면 b[5]-b[4] = 1
b[i] = b[i-1] + a[i]
BufferReader 이용
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Doit01_03 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int suNo = Integer.parseInt(st.nextToken());
int quizNo = Integer.parseInt(st.nextToken());
long[] s = new long[suNo+1];
st = new StringTokenizer(br.readLine());
for(int i = 1;i<=suNo; i++){
s[i] = s[i-1] + Integer.parseInt(st.nextToken());
}
for(int q=0;q<quizNo; q++){
st = new StringTokenizer(br.readLine());
int i = Integer.parseInt(st.nextToken());
int j = Integer.parseInt(st.nextToken());
System.out.println(s[j]-s[i-1]);
}
}
}
Scanner 이용
import java.io.IOException;
import java.util.Scanner;
;
public class Main {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
int []arr = new int[a+1];
for(int i=1;i<=a;i++){
arr[i]+=arr[i-1]+sc.nextInt();
}
for(int q=0;q<b;q++){
int i = sc.nextInt();
int j = sc.nextInt();
System.out.println(arr[j]-arr[i-1]);
}
}
}