하루 한 접시

[백준] 17298번 : 오큰수 [C#]

NaZZU 2024. 5. 22. 23:51

 

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
55
56
57
using System.IO;
using System.Text;
using System.Linq;
using System.Reflection.PortableExecutable;
using System.Security.Cryptography;
 
namespace 연습장
{
    internal class Program
    {
        static void Main(string[] args)
        {
            using var reader = new StreamReader(Console.OpenStandardInput());
            using var print = new StreamWriter(Console.OpenStandardOutput());
 
            _17298_boj boj = new _17298_boj();
 
            boj.boj_17298();
 
        }
    }
    internal class _17298_boj
    {
        public void boj_17298()
        {
            using var reader = new StreamReader(Console.OpenStandardInput());
            StringBuilder sb = new StringBuilder();
            int n = int.Parse(reader.ReadLine());
            int[] input = Array.ConvertAll(reader.ReadLine().Split(), int.Parse);
 
            int[] result = new int[n];
 
            Stack<int> stack = new Stack<int>();
 
            for (int i = n - 1; i >= 0; i--)
            {
                while (stack.Count > 0 && input[i] >= stack.Peek())
                {
                    stack.Pop();
                }
                if (stack.Count == 0)
                    result[i] = -1;
                else
                    result[i] = stack.Peek();
                stack.Push(input[i]);
            }
            foreach (var _ in result)
                sb.Append(_ + " ");
 
            if (sb[sb.Length - 1== ' ')
                sb.Remove(sb.Length - 11);
            Console.Write(sb);
        }
    }
}
 
 
cs

 

이번에는 너무 귀찮아서 스택을 직접 구현하지 않았다.

스택 관련해서 푼 문제중 의외로 제일 쉬웠다.

아파트 문제를 탑 문제처럼 풀었더니 아주 쉽게 풀 수 있었다.

다만 입력이 너무 많았던 것을 고려하지 못하여 시간초과가 났는데,

StreamReader와 StringBuilder를 사용하니 바로 해결되었다.