728x90
문제
https://www.acmicpc.net/problem/10810
N개의 바구니를 입력받고 M번 공을 넣는데, i번 바구니부터 j번 바구니까지 k번 공을 집어넣어야 하는 문제이다.
입력 출력
5 4 1 2 1 1 0
1 2 3
3 4 4
1 4 1
2 2 2
------------------------------------------------------------------------------------------------------------------
풀이
N개의 바구니와 넣을 횟수를 입력받은 뒤, 배열의 크기를 N으로 설정해주었다.
N번째 바구니는 N-1에 위치한 배열을 뜻하므로 i번 바구니부터 j번 바구니를 설정하는 변수인 n1, n2에 -1을 해주었다.
이후, for문 안에 한번 더 for문을 만들어서 입력받은 공을 배열에 넣어주었다.
(1) Scanner 사용
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int busket = sc.nextInt();
int count = sc.nextInt();
int n1, n2, ball = 0;
int array1[] = new int[busket];
for(int i=0;i<count;i++) {
n1 = sc.nextInt()-1;
n2 = sc.nextInt()-1;
ball = sc.nextInt();
for(int j=n1;j<=n2;j++) {
array1[j] = ball;
}
}
sc.close();
for(int i=0;i<array1.length;i++) {
System.out.print(array1[i]+" ");
}
}
}
------------------------------------------------------------------------------------------------------------------
(2) BufferdReader 사용
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer strtk = new StringTokenizer(br.readLine()," ");
int basket = Integer.parseInt(strtk.nextToken());
int count = Integer.parseInt(strtk.nextToken());
int n1, n2, ball = 0;
int array1[] = new int[basket];
for(int i=0;i<count;i++) {
strtk = new StringTokenizer(br.readLine()," ");
n1 = Integer.parseInt(strtk.nextToken())-1;
n2 = Integer.parseInt(strtk.nextToken())-1;
ball = Integer.parseInt(strtk.nextToken());
for(int j=n1;j<=n2;j++) {
array1[j] = ball;
}
}
br.close();
for(int i=0;i<array1.length;i++) {
System.out.print(array1[i]+" ");
}
}
}
728x90
'문제 풀이' 카테고리의 다른 글
[백준] 10810번: 공 넣기 - JAVA (자바) (0) | 2023.05.09 |
---|---|
[백준] 10813번: 공 바꾸기 - JAVA (자바) (0) | 2023.05.06 |
[백준] 2562번: 최댓값 - JAVA (자바) (0) | 2023.05.02 |
[백준] 10818번: 최소, 최대 - JAVA (자바) (0) | 2023.02.13 |
[백준] 10871번: X보다 작은 수 - JAVA (자바) (0) | 2023.02.10 |