본문 바로가기
알고리즘/백준 BOJ

[ BOJ/C# ] 11866 요세푸스 문제 0

by 왹져박사 2023. 9. 30.
728x90

https://www.acmicpc.net/problem/11866

 

11866번: 요세푸스 문제 0

첫째 줄에 N과 K가 빈 칸을 사이에 두고 순서대로 주어진다. (1 ≤ K ≤ N ≤ 1,000)

www.acmicpc.net

원형 큐를 만들어 푸는 문제인 듯하다. 

이번에는 다른 방법으로 풀어보고 싶어 생각나는 대로 풀어보았다. 

처음에는 시간초과가 떴는데,  index를 먼저  더해주었더니 k가 1일 경우에 무한루프로 돌아가는 것이 원인이었다. 

위치와 조건을 확실히 해주니 맞았다. 

using System;
using System.Text;

namespace B11866
{
    class Program
    {
        static void Main()
        {
            StreamReader sr = new StreamReader(Console.OpenStandardInput());
            StreamWriter sw = new StreamWriter(Console.OpenStandardOutput());
            StringBuilder sb = new StringBuilder();

            int[] nk = Array.ConvertAll(sr.ReadLine().Split(' '), int.Parse);
            int n = nk[0];
            int k = nk[1];
            Queue<int> q = new Queue<int>();
            int index = 1;
            for (int i = 1; i <= n; i++) q.Enqueue(i);
            sb.Append("<");
            while (q.Count > 0) //k번째 사람 제거하기
            {
                if (index == k)
                {
                    index = 1;
                    sb.Append(q.Dequeue());
                    if (q.Count > 0) sb.Append(", ");
                }
                else
                {
                    q.Enqueue(q.Dequeue()); //k번째 수가 아니면 다시 넣기
                    index++;
                }
            }
            sb.Append(">");
            sw.Write(sb);
            sr.Close();
            sw.Flush();
            sw.Close();
        }
    }
}

728x90

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

[ BOJ/C# ] 17626 Four Squares  (0) 2023.10.03
[ BOJ/C# ] 9012 괄호  (0) 2023.10.01
[ BOJ/C# ] 11650 좌표 정렬하기  (0) 2023.09.29
[ BOJ/C# ] 10814 나이순 정렬  (0) 2023.09.29
[ BOJ/C# ] 1181 단어 정렬  (0) 2023.09.28