SMALL

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

 

17298번: 오큰수

첫째 줄에 수열 A의 크기 N (1 ≤ N ≤ 1,000,000)이 주어진다. 둘째 줄에 수열 A의 원소 A1, A2, ..., AN (1 ≤ Ai ≤ 1,000,000)이 주어진다.

www.acmicpc.net

 


  • 문제


  • 문제풀이

while문의 조건에 따라 다음과 같이 작동한다.

 

1.

스택:3

result:null

조건 :x -> push

 

2.

스택:null

result:5

조건:3<5 -> pop

 

3.

스택:5

result:5

조건5>2 -> push

 

4.

스택:5 2

result:5

조건 5<7 -> pop

 

5.

스택:5

result:5 7

조건 : 2<7 -> pop

 

6.

스택: 7

result 5 7 7

조건: stack.count>0 -> pop

 

7.

스택:

result 5 7 7 -1

조건:


  • 코드 1
using System;
using System.Collections.Generic;
using System.Text;

class Program
{
    static void Main()
    {
        int N = int.Parse(Console.ReadLine());
        int[] input = Array.ConvertAll(Console.ReadLine().Split(), int.Parse);
        int[] result = new int[N];
        Stack<int> stack = new Stack<int>();

        for (int i = 0; i < N; i++)
        {
            while (stack.Count > 0 && input[stack.Peek()] < input[i])
                result[stack.Pop()] = input[i];

            stack.Push(i);
        }

        while (stack.Count > 0)
            result[stack.Pop()] = -1;

        Console.WriteLine(string.Join(" ", result));
    }
}

  • 후기

오랜만에 스택 문제를 풀었더니 재밌었다.

LIST

+ Recent posts