본문 바로가기

알고리즘/큐

1158번 요세푸스 문제

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;


public class Main {
	static Queue<Integer> queue=new LinkedList<Integer>();
	
	public static void main(String[] args) {
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(System.out));
		int removeCnt=0;

		StringBuffer sf=new StringBuffer();
		try {
			String tempTestCase=br.readLine();
			StringTokenizer st=new StringTokenizer(tempTestCase);
			sf.setLength(0);
			sf.append("<");
			int idx=1;
			int testCase=Integer.parseInt(st.nextToken());
			 removeCnt=Integer.parseInt(st.nextToken());
			 for(int j=1;j<=testCase;j++){
				 queue.add(j);
			 }

			 while(queue.size()>0){
				 if(idx==removeCnt){
					 sf.append(queue.poll());
					 idx=1;
					 if(queue.size()==0){
						 sf.append(">");
					 }else{
						 sf.append(", ");
					 }
				 }else{
					 queue.add(queue.poll());
					 idx++;
				 }
				
			 }
		
			 bw.write(sf.toString());
			 bw.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			if(br!=null){
				try {
					br.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				if(bw!=null){
					try {
						bw.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}
	}

}

'알고리즘 > ' 카테고리의 다른 글

10866번 큐  (0) 2020.06.30
10845번 큐  (0) 2020.06.30