문제 풀이

[백준] 10810번: 공 넣기 - JAVA (자바)

auyeol 2023. 5. 5. 14:36
728x90

 

 

문제

https://www.acmicpc.net/problem/10810

 

10810번: 공 넣기

도현이는 바구니를 총 N개 가지고 있고, 각각의 바구니에는 1번부터 N번까지 번호가 매겨져 있다. 또, 1번부터 N번까지 번호가 적혀있는 공을 매우 많이 가지고 있다. 가장 처음 바구니에는 공이

www.acmicpc.net

 

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