umilove98의 블로그

백준 1158 Java 본문

algorithm/백준

백준 1158 Java

umilove98 2021. 7. 23. 14:06
반응형

사람들의 앉은 모습을 ArrayList로 표현하여 N이 주어지면 0부터 N까지가 담겨있는 ArrayList 를 생성

0번자리는 필요 없으므로 index를 1부터 리스트의 마지막자리까지 계속 순환시킴

순환 도중 따로 k의 count를 세어 count가 k의 값이 될 때마다 해당 index의 원소값을 출력 ArrayList에 add함 

해당 자리의 사람은 삭제된 것으로 간주하기 위해 원소값을 0으로 바꾸어줌 

순환 도중 index의 원소값이 0인 자리는 없는 것으로 간주하기 위해 count를 증가하지 않음

출력할 ArrayList의 size가 N값과 같아지면 모든 사람이 제거된 것이므로 순환을 종료

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;

public class Main {

	public static void main(String[] args) throws IOException {
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
		String s = bf.readLine();
		StringTokenizer st = new StringTokenizer(s); 
		int n = Integer.parseInt(st.nextToken());
		int k = Integer.parseInt(st.nextToken());
		
		ArrayList<Integer> inList = new ArrayList<Integer>();
		ArrayList<Integer> outList = new ArrayList<Integer>();
		for(int i = 0; i < n + 1; i++) {
			inList.add(i);
		}

		int index = 1;
		int countk = 0;
		while(true) {
		
			if(inList.get(index) != 0) {	// 해당 index의 원소값이 0이 아닌경우(0인경우는 제거된 상태를 나타냄)에만 countk를 증가시킴
				countk++;
			}

			if(countk == k) {
				outList.add(inList.get(index));	// 해당 index가 k번째라면 index의 원소값을 outList의 맨 뒤에 집어넣고  
				inList.set(index, 0);	// 해당 자리는 삭제된 것으로 간주해야 하므로 원소값을 0으로 만들어줌
				countk = 0;	//k번째를 세는 카운트는 다시 0부터 시작하도록 되돌려줌
			}
			
			index++;
			
			if(index > inList.size()-1) {	//index가 inList의 1 ~ n을 계속 순회하도록 inList의 마지막index번호보다 커지면 1로 되돌려줌
				index = 1;
			}
			
			if(outList.size() == n) {	//outList의 크기가 n과 같다면 모든 사람이 제거된 것이므로 반복을 종료
				break;
			}
			
			
		}
		
		System.out.print("<"); // 출력
		for(int i = 0; i < outList.size(); i++) {
			if(i == 0) {
				System.out.print(outList.get(i));
			}else {
				System.out.print(", " + outList.get(i));
			}
			
		}
		System.out.print(">");
		

	}

}

 

 

 

반응형

'algorithm > 백준' 카테고리의 다른 글

백준 1312 Java  (0) 2021.07.26
백준 3004 Java  (0) 2021.07.26
백준 1094 Java  (0) 2021.07.23
백준 1059 Java  (0) 2021.07.22
백준 1037 Java  (0) 2021.07.22