본문 바로가기
Problem Solving/SWEA

[SWEA] 5789. 현주의 상자 바꾸기

by 테리는당근을좋아해 2020. 2. 23.

문제

1부터 N까지 0이 적혀진 상자가 있을 때, 일정한 규칙에 따라 상자의 번호를 바꾸는 문제

 

i번째 L과 R이 주어지면

 

L번째 상자부터 R번째 상자까지 i로 번호를 바꾼다.

 

다섯 개의 상자 0 0 0 0 0이 주어졌을 때,

 

첫번째 L과 R이 1, 3이라면

 

상자의 번호는 1 1 1 0 0 으로 바뀌고

 

두번째 L과 R이 2, 4라면

 

상자의 번호는 1 2 2 2 0 으로 바뀌게 된다.

 

풀이방법

주어진 N의 크기 만큼 배열을 만들고 i번째 명령어의 L과 R이 입력되었을 때,

 

배열의 L-1 부터 R-1의 원소를 i로 바꾸어 준다.

 

소스코드

package samsung;

import java.util.*;

public class s_5789 {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int test = sc.nextInt();
		
		for(int t = 1; t <= test; t++) {
			int n = sc.nextInt();
			int q = sc.nextInt();
			
			int[] a = new int[n+1];
			
			for(int i = 1; i <= q; i++) {
				int l = sc.nextInt();
				int r = sc.nextInt();
				
				for(int j = l; j <= r; j++) {
					a[j] = i;
				}
			}
			System.out.print("#" + t + " ");
			for(int i = 1; i <= n; i++) {
				System.out.print(a[i] + " ");
			}
			System.out.println();
		}
	}
}

 

댓글