코딩 테스트/BOJ

C# 1874 스택 수열

s0002 2023. 1. 18. 12:31

처음에 num의 값이 다르기만 하면 Push 하는 쪽으로 잘못 생각해서 어려웠다

오름차순이니까 Push 할 값이 num보다 작거나 같을 때 Push 해야 함

 

using System;
using System.Text;
using System.IO;
using System.Collections.Generic;


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

            //여기부터 작성 

            //입력 받을 숫자의 수
            int n = Convert.ToInt32(sr.ReadLine());

            Stack<int> stack = new Stack<int>(); 
            int pushNum = 1;
            int popCount = 0;

            for (int i = 0; i < n; i++)
            {
                int num = Convert.ToInt32(sr.ReadLine());

                while (pushNum<=num) //1이상 n이하의 정수 n개를 오름차순으로 Push
                {
                    sb.AppendLine("+");
                    stack.Push(pushNum); 
                    pushNum++;
                }
                //Pop하고 싶은 수가 Top(Peek)에 있어야 Pop 가능
                if (stack.Peek()==num)
                {
                    stack.Pop();
                    sb.AppendLine("-");
                    popCount++;
                }
            }

            //popCount가 n과 같지 않으면 불가능한 수열이다
            if (popCount == n)
                sw.WriteLine(sb);
            else
                sw.WriteLine("NO");

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

참고

AppendLine(): 결합할 문자열의 개수를 모르는 반복문 안에서 이용

https://chlee200530.tistory.com/118

 

C# 1874번 스택 수열

코드 : using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace _5 { internal class Program { static void Main(string[] args) { int N = Convert.ToInt32(Console.ReadLine()); Stack stack = new Stack(); StringBu

chlee200530.tistory.com

 

 

https://www.acmicpc.net/problem/1874

 

1874번: 스택 수열

1부터 n까지에 수에 대해 차례로 [push, push, push, push, pop, pop, push, push, pop, push, push, pop, pop, pop, pop, pop] 연산을 수행하면 수열 [4, 3, 6, 8, 7, 5, 2, 1]을 얻을 수 있다.

www.acmicpc.net

 

'코딩 테스트 > BOJ' 카테고리의 다른 글

C# 1439 뒤집기  (0) 2023.01.18
C# 5585 거스름돈  (0) 2023.01.18
C# 11659 구간 합 구하기4  (1) 2023.01.17
C# 11720 숫자의 합  (0) 2023.01.17
C# 10988 팰린드롬  (0) 2023.01.17