문제번호: 28278
문제명: 스택 2
문제링크: https://www.acmicpc.net/problem/28278
문제내용과 예제 입/출력은 위 문제 링크에서 확인해 주시기 바랍니다.
스택 자료구조를 이용하여 입력을 받아 command에 따른 행동을 수행하면 정답이 나옵니다.
시간초과가 뜰 줄 알았는데 스택의 시간복잡도가 이미 O(1)이라서 스택만으로도 충분했던 것 같습니다.
다음은 정답코드입니다.
public static void Main()
{
StreamReader sr = new StreamReader(Console.OpenStandardInput());
StreamWriter sw = new StreamWriter(Console.OpenStandardOutput());
Stack<int> stack = new Stack<int>();
int n = int.Parse(Console.ReadLine());
for (int i = 0; i < n; i++)
{
int[] input = Array.ConvertAll(Console.ReadLine().Split(), int.Parse);
int command = input[0];
switch(command)
{
case 1:
int x = input[1];
stack.Push(x);
break;
case 2:
if (stack.Count > 0)
{
int num = stack.Pop();
sw.WriteLine(num);
}
else
sw.WriteLine("-1");
break;
case 3:
sw.WriteLine(stack.Count);
break;
case 4:
if (stack.Count > 0)
sw.WriteLine("0");
else
sw.WriteLine("1");
break;
case 5:
if (stack.Count > 0)
{
int num = stack.Peek();
sw.WriteLine(num);
}
else
sw.WriteLine("-1");
break;
}
}
sr.Close();
sw.Close();
}'알고리즘 풀이' 카테고리의 다른 글
| [C#] 백준 15652번 문제풀이 (0) | 2026.01.21 |
|---|---|
| [C#] 백준 3273번 문제풀이 (0) | 2026.01.20 |
| [C#] 백준 14425번 문제풀이 (0) | 2026.01.18 |
| [C#] 백준 18258번 문제풀이 (0) | 2026.01.17 |
| [C#] 백준 1789번 문제풀이 (0) | 2026.01.16 |