백준 1138 한 줄로 서기 자바

꾸준하게 달리기~·2023년 6월 23일
0
post-thumbnail

문제는 다음과 같다
https://www.acmicpc.net/problem/1138

풀이는 다음과 같다.

import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

        //arr 이 주어짐
        //주어지는 arr 의 숫자는 해당 index의 사람이  자신보다 앞에있고 && 자신보다 키큰사람의 수임.
        //그리고 index 자체가 키의 크기임
        int N = Integer.parseInt(br.readLine());
        
        boolean[] visited = new boolean[N+1];
        int[] arr = new int[N+1];
        int[] answer = new int[N+1];
        
        StringTokenizer st = new StringTokenizer(br.readLine());
        
        for(int i = 1 ; i <= N ; i++) {
            int count = Integer.parseInt(st.nextToken());
            int index = 1;

            while(visited[index] || count != 0) { //나는 여기가 제일 어렵네.. while문은 true일때 동작한다 라고 기억하자
                if(!visited[index]) {
                    count--;
                    index++;
                }
                else {
                    index++;
                }
            }

            answer[index] = i;
            visited[index] = true;

        }

        for(int i = 1; i <= N ; i++) {
            bw.write(String.valueOf(answer[i]) + " ");
        }

        bw.flush();
        bw.close();
    }

}

헷갈렸던 부분은, wihle문은 소괄호 () 안이 true일때 동작한다.

풀이 로직은, 코드를 보면
내 키는 for 문의 i 이고,
코드에서,
숫자 count 는
내 앞에 나보다 키큰 친구가 몇명 있는지를 나타내주는 숫자이다
index 는
지금 키가 i인 친구가 들어갈 자리를 나타내주는 숫자이다
위의 코드에선 아래 내용이 가장 핵심이다.

if(!visited[index]) {
                    count--;
                    index++;
                }
                else {
                    index++;
                }

index가 비어있다면, count--, index++를 해준다.
비어있다 = 나보다 더 큰 친구들의 자리
비어있지 않다 = 이미 나보다 키가 더 작은 친구들이 선점


index가 비어있지 않다면, index++만 해주면 된다.
for문의 로직에 의해 나보다 더 큰 친구일 수는 없으므로.

profile
반갑습니다~! 좋은하루 보내세요 :)

0개의 댓글