1966번: 프린터 큐 (acmicpc.net)

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace _230122_1
{
    class Program
    {
        static void Main(string[] args)
        {
            StreamReader sr = new StreamReader(Console.OpenStandardInput());
            StreamWriter sw = new StreamWriter(Console.OpenStandardOutput());
            StringBuilder sb = new StringBuilder();

            int a = int.Parse(sr.ReadLine());
            List<int> answers = new List<int>();

            for (int i = 0; i < a; i++)
            {
                Queue<int[]> que = new Queue<int[]>();
                Queue<int> tmpQue = new Queue<int>();

                string[] arr0 = sr.ReadLine().ToString().Split();
                int N = int.Parse(arr0[0]);
                int M = int.Parse(arr0[1]);
                
                string[] arr1 = sr.ReadLine().ToString().Split(' ');

                for (int j = 0; j < N; j++)
                {
                    int[] arr2 = new int[2];
                    arr2[0] = int.Parse(arr1[j]);
                    arr2[1] = j;
                    que.Enqueue(arr2); //입력된 수의 순서를 확인하기 위해 정수 배열형을 값으로 가지는 큐를 만들어아 함(값과 인덱스)
                    tmpQue.Enqueue(arr2[0]);  //Max값을 비교하기 위해 정수형 값을 가지는 큐도 같이 만듦
                }

                //입력완료

                int cnt = 0;

                while(que.Count() != 0)
                {

                    int tmp = 0; 
                    bool isPrint = false;

                    if (que.Peek()[0] == tmpQue.Max()) //큐의 가장 앞 수를 최대값과 비교
                    {
                        tmp = que.Dequeue()[1];     //수의 입력 번호를 입시값에 저장
                        tmpQue.Dequeue();
                        cnt++; //큐에서 값이 빠져나갈 때마다 카운트
                        isPrint = true;             
                    }
                    else
                    {
                        que.Enqueue(que.Dequeue());
                        tmpQue.Enqueue(tmpQue.Dequeue()); //일치하지 않으면 두 큐에서 가장 앞의 값을 가장 뒤로 옮긴다
                    }

                    if(tmp == M && isPrint) //큐에서 빠져나간 값의 인덱스 값을 확인
                    {
                        answers.Add(cnt);
                        break;
                    }
                }      
            }

            foreach(int answer in answers)
            {
                sw.WriteLine(answer);
            }

            sr.Close();
            sw.Flush();
            sw.Close();
        }    
    }
}

큐나 스택도 Max로 최대 값을 구할 수 있다는 것을 알면 쉽게 풀 수 있는 문제였다.....

만약 정수 배열형을 값으로 가지는 큐의 각각의 값의 0번 인덱스의 값의 최대값을 구할 수 있다면 더 쉽게 풀 수 있을 것 같다.

'Algorithm > BOJ' 카테고리의 다른 글

C#) [BOJ] 2231 분해합  (0) 2023.01.23
C#) [BOJ] 2501 약수 구하기  (0) 2023.01.23
C#) [BOJ] 1302 베스트 셀러  (0) 2023.01.22
C#) [BOJ] 1940 주몽  (0) 2023.01.20
C#)[BOJ] 1159 농구경기  (0) 2023.01.20

+ Recent posts