관리 메뉴

Storage Gonie

(2) [C++, Java] 백준 No.1158 : 조세퍼스 문제 본문

알고리즘/백준풀이3. 큐

(2) [C++, Java] 백준 No.1158 : 조세퍼스 문제

Storage Gonie 2019. 4. 25. 15:14
반응형

문제

풀이

# C++

#include <iostream>
#include <queue>
using namespace std;

int main(void)
{
    ios::sync_with_stdio(false);

    int N;
    int K;
    cin >> N >> K;

    queue<int> q;

    // 1 ~ N의 숫자를 큐에 push하여 초기상태 만들기
    for (int i = 1 ; i <= N; i++)
        q.push(i);


    // ( pop push ) : K-1번 + pop : 1번 할 때 마다 front 값 출력하기.
    cout << "<";
    while(N--){
        
        
        for (int i = 0; i < K-1; i++){
            int num = q.front();
            q.pop();
            q.push(num);
        }

        if (!(N == 0))
            cout << q.front() << ", ";
        else
            cout << q.front();
        
        q.pop();
    }
    cout << ">";
}

 

# Java

import java.util.*;

public class Main {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();
        StringBuilder sb = new StringBuilder();
        sb.append('<');
        Queue<Integer> queue = new LinkedList<Integer>();
        for (int i=1; i<=n; i++) {
            queue.offer(i);
        }
        for (int i=0; i<n-1; i++) {
            for (int j=0; j<m-1; j++) {
                queue.offer(queue.poll());
            }
            sb.append(queue.poll() + ", ");
        }
        sb.append(queue.poll() + ">");
        System.out.println(sb);
    }
}
반응형
Comments