2024-04-03 00:50:52

 

승환이가 지금 서있는 줄과, 일방통행만 가능한 줄이 있을 때, 승환이의 차례가 올 수 있는지 구하는 문제이다.

승환이가 서있는 줄은 순서가 무작위로 섞여있는 상태이고,  승환이의 차례는 맨 마지막이다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
using System.IO;
using System.Text;
using System.Linq;
using System.Reflection.PortableExecutable;
using System.Security.Cryptography;
 
namespace 연습장
{
    internal class Program
    {
        //static List<int> stack = new List<int>();
        static StringBuilder sb = new StringBuilder();
        static void Main(string[] args)
        {
            using var reader = new StreamReader(Console.OpenStandardInput());
            using var print = new StreamWriter(Console.OpenStandardOutput());
 
            int N = int.Parse(reader.ReadLine());
 
            int[] line = Array.ConvertAll(reader.ReadLine().Split(), int.Parse);
 
            Stack<int> stack1 = new Stack<int>();
            Stack<int> stack2 = new Stack<int>();
 
            int cnt = 1;
 
            foreach (int people in line)
            {
                stack1.Push(people);
 
                if (people == cnt)
                {
                    int stacklen = stack1.Count();
                    for (int i = 0; i < stacklen; i++)
                    {
                        if (stack1.Peek() == cnt)
                        {
                            stack2.Push(stack1.Pop());
                            cnt++;
                        }
                    }
                }    
            }
 
            if (stack1.Count() == 0)
                print.WriteLine("Nice");
            else print.WriteLine("Sad");
        }
    }
}
cs

 

승환이가 있는 줄의 사람들을 일단 전부 일방통행만 가능한 줄 (스택1)로 넣는다.

넣는 도중 첫번째 순번의 사람이 오면 그 사람을 간식 받는 줄(스택2)로 보낸다.

그리고 다음 순번의 사람이 스택1의 맨 앞에 있는지 검사하고, 있다면 스택2로 보낸다.

이 부분을 while문으로 무한루프 돌리면서 stack1의 peek가 cnt가 아니라면 break시키는 방법을 사용하면 반복 횟수를 줄일 수 있을것 같다.

아무튼 결과적으로 stack1의 사람이 모두 빠져나갔다면 승환이는 간식을 받은거고, 아니면 못받은 걸로 출력을 해준다.

 

 

'하루 한 접시' 카테고리의 다른 글

[백준] 1092번: 배 [C#]  (0) 2024.04.05
[백준] 18258번: 큐 2 [C#]  (0) 2024.04.03
[백준] 10773번: 제로 [C#]  (0) 2024.04.01
[백준] 28278번: 스택 2 [C#]  (0) 2024.04.01
[백준] 13909번: 창문 닫기 [C#]  (0) 2024.04.01