하루 한 접시
[백준] 1874번 : 스택 수열 [C#]
NaZZU
2024. 5. 16. 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
|
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());
_1874_boj boj = new _1874_boj();
boj.boj_1874();
}
}
internal class _1874_boj
{
static string[] stack;
static int top = -1;
static int cur = 1;
public void boj_1874()
{
StringBuilder sb = new StringBuilder();
int n = int.Parse(Console.ReadLine());
stack = new string[n];
string[] arr = new string[n];
for (int i = 0; i < n; i++)
arr[i] = Console.ReadLine();
for (int i = 0; i < n; i++)
{
if (isStackEmpty())
sb.Append(push(cur) + '\n');
if (peek() != arr[i])
{
for (int j = cur; j <= int.Parse(arr[i]); j++)
sb.Append(push(j) + '\n');
}
if (peek() != arr[i] && cur > int.Parse(arr[i]))
{
sb.Clear();
sb.Append("NO");
break;
}
sb.Append(pop() + '\n');
}
if (sb[sb.Length - 1] == '\n')
sb.Remove(sb.Length - 1, 1);
Console.WriteLine(sb);
}
public bool isStackEmpty()
{
bool res = false;
if (top == -1)
res = true;
return res;
}
public string push(int data)
{
stack[++top] = data.ToString();
cur++;
return "+";
}
public string pop()
{
if (isStackEmpty())
return null;
stack[top--] = null;
return "-";
}
public string peek()
{
return stack[top];
}
}
}
|
cs |
스택의 가장 위의 있는 값이 arr배열의 값과 같지 않다면 1부터 증가시켜 가며 스택에 push를 하고, 지금까지 스택에 넣어진 수의 최고값을 따로 저장해 주었다.
이후 스택의 가장 위의 값이 arr배열의 값과 일치한다면 pop을 해주었다.
5를 pop 해준 다음 4를 pop 해주어야 한다. 예제 2에 나온 것 처럼 3을 pop할 수 는 없다.
그렇기 때문에 예외사항은 저장해둔 최고값보다 값이 작으면서, 스택의 가장 위의 값과 일치 하지 않는 것으로 해 주었다.