전체 글 (165)
2024-05-31 17:34:31

패키지는 class를 기능별로 묶어서 그룹의 이름을 붙인 것이다.

 

상위패키지.하위패키지.클래스로 이루어진 클래스의 이름의 일부분이기도 한데,

이 때문에 클래스의 이름이 같더라도 패키지의 이름이 다르다면 다른 클래스로 취급된다.

 

클래스는 선언할 때 패키지를 결정하는데, (package packageName) 결정한 클래스와 다른 패키지(폴더) 안에 넣으면 실행되지 않는다 

 

다른 패키지에 있는 클래스를 사용하는 경우 두 가지 방법이 존재한다.

 

 

첫 번째 방법은 패키지 명이 포함된 전체 클래스 이름으로 사용한다.

java.util.Scanner sc = new java.util.Scanner(System.in);

이런 식으로 인스턴스를 만들어서 사용해도 돼지만, 사용하려는 것이 정적 필드/메서드라면 인스턴스 생성 없이 사용해도 된다.

 

두 번째 방법은 import문을 사용하여 패키지를 사용하는 것이다.

패키지 선언과 클래스 선언 사이에 import 상위패키지.하위패키지.클래스; 로 패키지를 지정한다.

ex) impoert java.util.Scanner();

Scanner sc = new Scnaner(Sytem.in);

사용하려는 패키지가 여러개인 경우 클래스별로 import 하는 대신 import.패키지명.*; 을 사용하면 해당 패키지의 모든 클래스를 사용 가능하다.

이 경우 import로 지정된 패키지의 하위 패키지는 import 대상이 아니므로, 사용하고자 한다면 따로 import 해주어야 한다.

 

서로 다른 패키지에 동일한 이름의 클래스가 있는 경우, import문을 사용하였더라도 패키지 이름 전체를 사용해서 기술해야 한다.

 

'생각 두 접시' 카테고리의 다른 글

[java] Getter / Setter  (0) 2024.05.31
[java] 접근 제한자  (0) 2024.05.31
중복 요소 제거와 특정 키를 기준으로 오름차순 정렬하기  (0) 2024.03.20
static에 관하여  (0) 2024.03.20
c#의 빠른 입출력  (0) 2024.03.20
2024-05-23 23:28:52

 

 

 

 

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
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());
 
            _2504_boj boj = new _2504_boj();
 
            boj.boj_2504();
 
        }
    }
    internal class _2504_boj
    {
        public void boj_2504()
        {
            string input = Console.ReadLine();
            int result = 0;
            int temp = 1;
            Stack<char> stack = new Stack<char>();
 
            for (int i = 0; i < input.Length; i++)
            {
                if (input[i] == '[' || input[i] == '(')
                {
                    temp *= input[i] == '[' ? 3 : 2;
                    stack.Push(input[i]);
                    continue;
                }
                if (input[i] == ']')
                {
                    if (stack.Count > 0 && stack.Peek() == '[')
                    {
                        if (i > 0 && input[i - 1== '[')
                        {
                            result += temp;
                            temp /= 3;
                            stack.Pop();
                        }
                        else
                        {
                            temp /= 3;
                            stack.Pop();
                        }
                    }
                    else
                    {
                        result = 0;
                        break;
                    }
                }
                if (input[i] == ')')
                {
                    if (stack.Count > 0 && stack.Peek() == '(')
                    {
                        if (i > 0 && input[i - 1== '(')
                        {
                            result += temp;
                            temp /= 2;
                            stack.Pop();
                        }
                        else
                        {
                            temp /= 2;
                            stack.Pop();
                        }
                    }
                    else
                    {
                        result = 0;
                        break;
                    }
                }
            }
            Console.WriteLine(stack.Count > 0 ? 0 : result);
        }
    }
}
 
 
cs

 

 

2024-05-22 23:51:52

 

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를 사용하니 바로 해결되었다.

 

2024-05-22 22:12:01

며칠전 올린 탑 문제와 비슷한 문제이다.

탑 문제는 가장 가까운 신호를 수신하는 탑의 번호를 출력하는 거라면

이번 문제는 한 탑보다 큰 탑이 올때 까지의 모든 탑(아파트) 의 개수를 구해서 더하여 출력하는 문제이다.

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
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());
 
            _6198_boj boj = new _6198_boj();
 
            boj.boj_6198();
 
        }
    }
        internal class _6198_boj
    {
        public void boj_6198()
        {
            int n = int.Parse(Console.ReadLine());
            Stack stack = new Stack(n);
 
            string[] input = new string[n];
            for (int i = 0; i < n; i++)
                input[i] = Console.ReadLine();
 
            long result = 0;
 
            for (int i = 0; i < n; i ++)
            {
                while (stack.top >= 0 && int.Parse(input[int.Parse(stack.Peek())]) <= int.Parse(input[i]))
                {
                    stack.Pop();
                }
 
                result += stack.size;
                stack.Push(i.ToString());
 
            }
            Console.WriteLine(result);
        }
    }
    public class Stack
    {
        public string[] stack;
        public int top = -1;
        public int size = 0;
        public Stack(int n)
        {
            stack = new string[n];
        }
        public void Push(string data)
        {
            if (top != stack.Length - 1)
            {
                top += 1;
                stack[top] = data;
                size++;
            }
        }
        public string Pop()
        {
            string result = null;
            if (top != -1)
            {
                result = stack[top];
                stack[top--= null;
                size--;
            }
 
            return result;
        }
        public string Peek()
        {
            string result = null;
            if (top != -1)
                result = stack[top];
 
            return result;
        }
    }
}
 
 
cs

 

입력받은 배열의 0번지부터 n - 1번지까지 돌아가며 스택의 맨 위값과 비교하여 같거나 작다면 자신보다 작은 값이 나올때까지 계속 pop해주었다.

pop을 모두 수행 한 이후 (stack이 모두 비게됨 / stack의 맨 위값이 현재 배열의 값보다 큼)

남은 스택의 원소 만큼 결과값에 넣어 주었다. (여기서는 stack.size로 따로 변수를 만들어 주었으나, stack.top + 1을 사용하면 좋을 듯 하다.)

(이 과정은 현재 아파트의 옥상을 볼 수 있는 아파트의 수를 구하는 과정이다.)

마지막으로 현재 아파트의 높이를 가리키는 주소를 스택에 넣어주고 다음 회차로 진행해 주었다.

또한 주어지는 결과값이 매우 크기때문에 (단적인 예로 799,999 + 799,998 + 799,997 .... + 1) 결과를 저장할 변수를 int형으로 하면 오버플로우로 인한 오류가 난다.

그렇기 때문에 long형을 사용해야 한다.

'하루 한 접시' 카테고리의 다른 글

[백준] 2504번 : 괄호의 값 [C#]  (0) 2024.05.23
[백준] 17298번 : 오큰수 [C#]  (0) 2024.05.22
[백준] 10799번 : 쇠막대기 [C#]  (0) 2024.05.21
[백준] 10845번 : 큐 [C#]  (0) 2024.05.21
[백준] 28279번: 덱 2 [C#]  (0) 2024.05.20
2024-05-21 01:09:29

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
92
93
94
95
96
97
98
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());
 
            _10799_boj boj = new _10799_boj();
 
            boj.boj_10799();
 
        }
    }
        internal class _10799_boj
    {
        public void boj_10799()
        {
            string sticks = Console.ReadLine();
            Stack stack = new Stack();
            
            stack.stack = new string[sticks.Length];
 
            int result = 0;
 
            for (int i = 0; i < sticks.Length; i++)
            {
                if (sticks[i] == '(')
                {
                    stack.Push("(");
                    continue;
                }
                if (sticks[i] == ')' && i >= 1)
                {
                    if (sticks[i - 1== '(')
                    {
                        stack.Pop();
                        result += stack.size;
                        continue;
                    }
                    else
                    {
                        stack.Pop();
                        result++;
                        continue;
                    }
                }
            }
            Console.WriteLine(result);
        }
    }
    public class Stack
    {
        public int size;
        public string[] stack;
        public int top = -1;
        public void Push(string data)
        {
            if (IsStackFull())
                return;
            stack[++top] = data;
            size++;
        }
        public string Pop()
        {
            string res = null;
            if (IsStackEmpty())
                return res;
            res = stack[top--];
            size--;
            return res;
        }
        public bool IsStackFull()
        {
            bool res = false;
            if (top == stack.Length - 1)
                res = true;
            return res;
        }
        public bool IsStackEmpty()
        {
            bool res = false;
            if (top == -1)
                res = true;
            return res;
        }
 
    }
}
 
 
cs

 

입력받은 문자열을 하나씩 되짚어가며

여는 괄호 " ( " 를 만나면 일단 스택에 저장한다.

이후 닫는 괄호 " ) " 를 만나게 되면       (0번 인덱스에 오는 닫는 괄호는 의미 없으니 거르는 코드를 추가해 주었다)

바로 직전 괄호가 여는 괄호인 경우 : 스택에서 해당 괄호를 제거 해 주고 스택에 남은 여는 괄호만큼 결과값에 추가

직전 괄호가 여는 괄호가 아닐 경우 : 스택에서 가장 앞에 있는 여는 괄호를 제거해주고, 결과값에 1 추가

이런식으로 진행해 주었더니 한번에 정답을 얻을 수 있었다

 

 

'하루 한 접시' 카테고리의 다른 글

[백준] 17298번 : 오큰수 [C#]  (0) 2024.05.22
[백준] 6198번 : 옥상 정원 꾸미기 [C#]  (0) 2024.05.22
[백준] 10845번 : 큐 [C#]  (0) 2024.05.21
[백준] 28279번: 덱 2 [C#]  (0) 2024.05.20
[백준] 2493번 : 탑 [C#]  (0) 2024.05.20
2024-05-21 00:21:16

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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
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());
 
            _10845_boj boj = new _10845_boj();
 
            boj.boj_10845();
 
        }
    }
        internal class _10845_boj
    {
        public void boj_10845()
        {
            StringBuilder sb = new StringBuilder();
            Queue queue = new Queue();
            queue.n = int.Parse(Console.ReadLine());
            queue.queue = new string[queue.n];
 
            for (int i = 0; i < queue.n; i++)
            {
                string[] input = Console.ReadLine().Split();
                switch(input[0])
                {
                    case "push":
                        queue.Push(input[1]);
                        break;
                    case "pop":
                        sb.Append(queue.Pop() + "\n");
                        break;
                    case "size":
                        sb.Append(queue.size + "\n");
                        break;
                    case "empty":
                        sb.Append(queue.IsQueueEmpty() ? "1\n" : "0\n");
                        break;
                    case "front":
                        
                        sb.Append(queue.Front() + "\n");
                        break;
                    case "back":
                        sb.Append(queue.Back() + "\n");
                        break;
                }
            }
            if (sb.Length >= 1 && sb[sb.Length - 1== '\n')
                sb.Remove(sb.Length - 11);
            Console.WriteLine(sb);
        }
    }
    public class Queue
    {
        public int n;
        public int front = -1;
        public int rear = -1;
        public string[] queue;
        public int size = 0;
        public void Push(string data)
        {
            if (IsQueueFull())
                return;
            rear++;
            queue[rear] = data;
            size++;
        }
        public string Pop()
        {
            string res = "-1";
            if (IsQueueEmpty())
                return res;
            front++;
            res = queue[front];
            queue[front] = null;
            size--;
            return res;
        }
        public bool IsQueueEmpty()
        {
            bool res = false;
            if (rear == front)
                res = true;
            return res;
        }
        public bool IsQueueFull()
        {
            bool res = false;
            if (rear == n - 1)
                res = true;
            return res;
        }
        public string Front()
        {
            string res = "-1";
            if (IsQueueEmpty())
                return res;
            res = queue[front + 1];
            return res;
        }
        public string Back()
        {
            string res = "-1";
            if (IsQueueEmpty())
                return res;
            res = queue[rear];
            return res;
        }
    }
}
 
 
cs

 

출력값들을 StringBuilder형 변수에 넣고 출력하는 과정에서 마지막에 생기는 공백을 없애기 위한 코드인

if (sb[sb.Length - 1== '\n')

이 코드가 sb의 길이가 0인 경우 (n번의 입력동안 push만 한 경우) indexOufOfRange 에러가 나는 실수를 했다.

2024-05-20 23:51:33

 

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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
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());
 
            _28279_boj boj = new _28279_boj();
 
            boj.boj_28279();
 
        }
    }
        internal class _28279_boj
    {
        public void boj_28279()
        {
            StringBuilder sb = new StringBuilder();
            Deque deque = new Deque();
            deque.n = int.Parse(Console.ReadLine()) + 1; // 덱이 가득 찼는지 판별
하기 위해 빈공간을 하나 사용하므로 하나만큼 공간을 더 주었다. (n번동안 push만 할 경우 에러 방지)
 
            deque.deque = new string[deque.n];
 
            for (int i = 0;i < deque.n - 1; i++)
            {
                string[] input = Console.ReadLine().Split();
                switch(input[0])
                {
                    case "1":
                        deque.PushFront(input[1]);
                        break;
                    case "2":
                        deque.PushBack(input[1]);
                        break;
                    case "3":
                        sb.Append(deque.PopFront() + "\n");
                        break;
                    case "4":
                        sb.Append(deque.PopBack() + "\n");
                        break;
                    case "5":
                        sb.Append(deque.size + "\n");
                        break;
                    case "6":
                        sb.Append(deque.IsDequeEmpty() ? "1\n" : "0\n");
                        break;
                    case "7":
                        sb.Append(deque.Bottom() + "\n");
                        break;
                    case "8":
                        sb.Append(deque.peek() + "\n");
                        break;
                }
            }
            Console.Write(sb);
        }
 
 
    }
    public class Deque
    {
        public int n; // 덱의 크기를 결정하는 변수
        public string[] deque; // 덱을 구현할 배열
        public int back = -1; // 가장 뒤에있는 숫자의 주소를 가리킬 변수
        public int front = 0; // 가장 앞에있는 숫자의 주소를 가리킬 변수
        public int size = 0; // 덱의 원소의 수를 저장하는 변수
        public void PushFront(string data)
        {
            if (IsDequeFull())
                return;
            front = (front - 1 + n) % n; // 0 - 1 + n을 n으로 나누면 n - 1이 나온다 (다음 회차엔 n - 2, n - 3 ...)
            deque[front] = data;
            size++;
        }
        public void PushBack(string data)
        {
            if (IsDequeFull())
                return;
            back = (back + 1) % n;
            deque[back] = data;
            size++;
        }
        public bool IsDequeEmpty()
        {
            bool res = false;
            if ((back + 1) % n == front)
                res = true;
            return res;
        }
        public bool IsDequeFull()
        {
            bool res = false;
            if ((back + 2) % n == front)
                res = true;
            return res;
        }
        public string PopFront()
        {
            string res = "-1";
            if (IsDequeEmpty())
                return res;
            res = deque[front];
            deque[front] = null;
            front = (front + 1) % n;
            size--;
            return res;
        }
        public string PopBack()
        {
            string res = "-1";
            if (IsDequeEmpty())
                return res;
            if (back == -1) // 이 코드가 없으면 PushBack 메소드를 진행하지 않고 PopBack 메소드를 실행할 때 에러가 남
                back = n - 1; // 어차피 PushBack을 실행한 적이 없다면 가장 뒤에있는 원소의 주소는 n - 1
            res = deque[back];
            deque[back] = null;
            back = (back - 1 + n) % n;
            size--;
            return res;
        }
        public string Bottom()
        {
            string res = "-1";
            if (IsDequeEmpty())
                return res;
            res = deque[front];
            return res;
        }
        public string peek()
        {
            string res = "-1";
            if (IsDequeEmpty())
                return res;
            if (back == -1)
            {
                res = deque[n - 1];
                return res;
            }
            res = deque[back];
            return res;
        }
    }
}
 
 
cs

은근히 어려웠다...

덱을 구현하기 위해 원형 큐를 응용한 것까지는 좋았지만, 큐처럼 front는 항상 빈공간(null)을 가리키려고 해서 더욱 헷갈렸던 것 같다.

 

 

'하루 한 접시' 카테고리의 다른 글

[백준] 10799번 : 쇠막대기 [C#]  (0) 2024.05.21
[백준] 10845번 : 큐 [C#]  (0) 2024.05.21
[백준] 2493번 : 탑 [C#]  (0) 2024.05.20
[백준] 1874번 : 스택 수열 [C#]  (0) 2024.05.16
[백준] 요세푸스 문제 0 [C#]  (0) 2024.05.14
2024-05-20 18:59:53

 

 

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
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());
 
            _2493_boj boj = new _2493_boj();
 
            boj.boj_2493();
 
        }
    }
    internal class _2493_boj
    {
        public void boj_2493()
        {
            var reader = new StreamReader(Console.OpenStandardInput());
            var print = new StreamWriter(Console.OpenStandardOutput());
            var sb = new StringBuilder();
            Stack tower = new Stack();
            tower.size = int.Parse(reader.ReadLine());
            tower.stack = new string[tower.size];
 
            string[] input = reader.ReadLine().Split();
            string[] result = new string[tower.size];
 
            for (int i = 0; i < tower.size; i++)
            {
                while (tower.top != -1 && int.Parse(input[i]) > int.Parse(input[int.Parse(tower.peek())]))
                {
                    tower.pop();
                }
                sb.Append(tower.top == -1 ? "0" : (int.Parse(tower.peek()) + 1).ToString());
                if (i != tower.size - 1)
                    sb.Append(' ');
                tower.push(i.ToString());
            }
 
            print.Write(sb);
            print.Flush();
 
        }
    }
    public class Stack
    {
        public int top = -1;
        public string[] stack;
        public int size;
 
        public void push(string data)
        {
            stack[++top] = data;
        }
        public string pop()
        {
            string res = null;
            if (top != -1)
            {
                res = stack[top];
                stack[top--= null;
            }
 
            return res;
        }
        public string peek()
        {
            string res = null;
            if (top != -1)
                res = stack[top];
            return res;
        }
 
    }
}
 
 
cs

 

 

 

'하루 한 접시' 카테고리의 다른 글

[백준] 10845번 : 큐 [C#]  (0) 2024.05.21
[백준] 28279번: 덱 2 [C#]  (0) 2024.05.20
[백준] 1874번 : 스택 수열 [C#]  (0) 2024.05.16
[백준] 요세푸스 문제 0 [C#]  (0) 2024.05.14
[백준] 2164번: 카드2 [C#]  (0) 2024.05.14
2024-05-16 23:51:59

 

 

 

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 - 11);
 
            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할 수 는 없다.

그렇기 때문에 예외사항은 저장해둔 최고값보다 값이 작으면서, 스택의 가장 위의 값과 일치 하지 않는 것으로 해 주었다.

 

'하루 한 접시' 카테고리의 다른 글

[백준] 28279번: 덱 2 [C#]  (0) 2024.05.20
[백준] 2493번 : 탑 [C#]  (0) 2024.05.20
[백준] 요세푸스 문제 0 [C#]  (0) 2024.05.14
[백준] 2164번: 카드2 [C#]  (0) 2024.05.14
[백준] 1759번: 암호 만들기 [C#]  (0) 2024.05.13
2024-05-14 19:34:01

 

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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
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());
 
            _11866_boj boj = new _11866_boj();
 
            boj.boj_11866();
 
        }
    }
        internal class _11866_boj
    {
        static int[] input;
        static string[] queue;
        static int n;
        static int rear = 0;
        static int front = 0;
        public void boj_11866()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<");
            input = Array.ConvertAll(Console.ReadLine().Split(), int.Parse);
            queue = new string[input[0+ 1];
            n = input[0];
 
            for (int i = 1; i <= n; i++)
                queue[i] = i.ToString();
 
            rear = n;
 
            int cnt = 0;
            int left = n;
            while(left >= 1)
            {
                string temp = dequeue();
                cnt++;
                if (left == 1)
                {
                    sb.Append(temp);
                    break;
                }
                if (cnt == input[1])
                {
                    sb.Append(temp);
                    if (left > 1)
                        sb.Append(", ");
                    cnt = 0;
                    left--;
                    continue;
                }
                enqueue(temp);
                
            }
            sb.Append(">");
            if (sb[sb.Length - 1== '\n')
                sb.Remove(sb.Length - 11);
            Console.WriteLine(sb);
        }
        public bool isQueueFull()
        {
            bool res = false;
            if (rear % (n + 1== front)
                res = true;
 
            return res;
        }
        public bool isQueueEmpty()
        {
            bool res = false;
            if (rear == front)
                res = true;
 
            return res;
        }
        public void enqueue(string data)
        {
            if (isQueueFull())
                return;
 
            rear = (rear + 1) % (n + 1);
            queue[rear] = data;
 
        }
        public string dequeue()
        {
            if (isQueueEmpty())
                return null;
 
            front = (front + 1) % (n + 1);
            string data = queue[front];
            queue[front] = null;
            return data;
        }
    }
}
 
 
cs

 

제거 간격이 1인 경우 마지막 문자가 2번 출력되는 오류가 있었다.

그래서 그냥 마지막 문자를 넣으면 반복문에서 나가는 방향으로 고쳐줬다.

 

 

 

'하루 한 접시' 카테고리의 다른 글

[백준] 2493번 : 탑 [C#]  (0) 2024.05.20
[백준] 1874번 : 스택 수열 [C#]  (0) 2024.05.16
[백준] 2164번: 카드2 [C#]  (0) 2024.05.14
[백준] 1759번: 암호 만들기 [C#]  (0) 2024.05.13
[백준] 10828번: 스택 [C#]  (0) 2024.05.12