[백준풀이]24511 사이클에 대한 고뇌, 고찰

SeoYehJoon·2023년 11월 11일
post-thumbnail



풀코드

package baek_2346;

import java.io.*;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.StringTokenizer;


public class Balloon 
{

    public static void main(String[] args) throws IOException 
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();

        Deque<Balloon1> queue = new ArrayDeque<>();

        int N = Integer.parseInt(br.readLine());
        
        StringTokenizer st = new StringTokenizer(br.readLine());
        
        int[] moveset = new int[N];
        for(int i=0;i<N;i++)
        {
        	moveset[i] = Integer.parseInt(st.nextToken());
        }
        
        sb.append("1 ");
        int action = moveset[0];
       
        for(int i =1; i < N; i++)
        {
        	queue.add(new Balloon1( i + 1 , moveset[i]) );
        }
       
        while(!queue.isEmpty())
        {
        	if(action > 0)
        	{
        		for(int i=1;i<action;i++)
        		{
        			queue.add(queue.poll());
        		}
        		Balloon1 now = queue.poll();
        		action = now.moving;
        		sb.append(now.label+" ");
        	}
        	else
        	{
        		for(int i=1;i<-action;i++)
        		{
        			queue.addFirst(queue.pollLast());
        		}
        		
        		Balloon1 now = queue.pollLast();
        		action = now.moving;
        		sb.append(now.label+" ");
        	}
        }
        System.out.println(sb);
    }
}


class Balloon1{
    int label;
    int moving;

    public Balloon1(int index, int numValue) 
    {
        this.label = index;
        this.moving = numValue;
    }
}





풀이


백준 input값을 미리 담아둠을 보아라

그이후에는 Balloon1자료형을 담는 큐에 값을 채우자.

이제 코드의 핵심 부분을 보자


1. 1은 미리 빼두고 시작한다.



양수 방향으로 움직일때

아래 그림에서 보이듯이 양의 움직임이 나왔을때는 ' 왼쪽 ' 에서 꺼내서 오른쪽으로 집어넣자. 그리고 타겟값이 나왔을때 ' 왼쪽 ' 에서 꺼낸다. 아래 그림은 양수인 3만큼 움직일때의 경우이다.




음수 방향으로 움직일때


아래 그림에서 보이듯이 음의 움직임이 나왔을때는 ' 오른쪽 ' 에서 꺼내서 오른쪽으로 집어넣자. 그리고 타겟값이 나왔을때 ' 오른쪽 ' 에서 꺼낸다. 아래 그림은 음수인 -2 만큼 움직일때의 경우이다.




사이클(순환구조)를 쉽게 이해해볼까?

0개의 댓글