C#/알고리즘

11. 2504번 괄호의 값 (해결)

dev_sr 2020. 6. 22. 00:00

괄호가 먼저 올바른지 따지고

맞으면 괄호 값을 계산함

 

짝이 맞는 괄호 차례가 오면 괄호를 지우고 해당하는 숫자를 스택에 넣고

다음 차례에 숫자가 오면 int 변수(num)를 만들어서 짝이 맞는 괄호가 올때까지 지워가면서 변수에 넣어줌

foreach를 돌 때마다 num이 0이 아니면 값을 스택에 넣어주고 초기화한다

짝이 맞는 차례가 오면 변수에 x2나 x3을 해줌

 

그리고 스택에 쌓여있는 숫자들을 한번에 더해서 출력해줌

 

 

아무튼 극혐

using System;
using System.Collections.Generic;


namespace _2504
{
    class Program
    {
        static void Main(string[] args)
        {
            string input = Console.ReadLine();
            Bracket bracket = new Bracket(input);
            if (!bracket.Judge()) Console.WriteLine(0);
            else Console.WriteLine(bracket.Caculate());
        }
    }

    class Bracket
    {

        public string input;

        Stack<string> stack = new Stack<string>();

        public Bracket(string input)
        {
            this.input = input;
        }

        public bool Judge()
        {
            foreach (var br in this.input)
            {

                if (br == '(' || br == '[')
                {

                    this.stack.Push(br.ToString());
                }

                if (br == ')')
                {
                    if (stack.Count != 0 && this.stack.Peek() == "(")
                    {
                        this.stack.Pop();
                    }
                    else
                    {
                        return false;
                    }

                }

                if (br == ']')
                {
                    if (stack.Count != 0 && this.stack.Peek() == "[")
                    {
                        this.stack.Pop();
                    }
                    else
                    {
                        return false;
                    }

                }

            }

            return (stack.Count == 0) ? true : false;
        }


        public int Caculate()
        {
            int num = 0;

            foreach (var br in this.input)
            {
                if (br == '(' || br == '[')
                {
                    this.stack.Push(br.ToString());
                }

                if (br == ')')
                {
                    if (this.stack.Peek() == "(")
                    {
                        this.stack.Pop();
                        this.stack.Push("2");
                    }
                    else
                    {
                        while (this.stack.Peek() != "(")
                        {
                            num += int.Parse(this.stack.Pop().ToString());

                        }
                        if (this.stack.Peek() == "(")
                        {
                            this.stack.Pop();
                            num *= 2;
                        }
                    }
                }

                if (br == ']')
                {
                    if (this.stack.Peek() == "[")
                    {
                        this.stack.Pop();
                        this.stack.Push("3");
                    }
                    else
                    {
                        while (this.stack.Peek() != "[")
                        {
                            num += int.Parse(this.stack.Pop().ToString());

                        }
                        if (this.stack.Peek() == "[")
                        {
                            this.stack.Pop();
                            num *= 3;
                        }
                    }
                }

                if (num != 0)
                {
                    stack.Push(num.ToString());
                    num = 0;
                }

            }


            int sum = 0;
            foreach (var data in stack)
            {
                sum += int.Parse(data);
            }

            return sum;

        }
    }
}

 

-------------------------------------------------------------------------------------------------------------------------------

 

값은 올바르게 받고 올바르지 못한건 0으로 나오게 하고

( ) [ ] 에서 점수 + 하는 것도 알겠는데..

(( )) ([ ]) 이걸 어떻게 점수를 적용해야하는 지 아직 잘 모르겠다..

스택을 어떻게 써먹지????

 

 

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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.Eventing.Reader;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
 
namespace _2504
{
    class Program
    {
        static void Main(string[] args)
        {
            int count1 = 0;  //완성해야할 괄호 개수
            int count2 = 0;
 
            int grade1 = 0;
            int grade2 = 0;
            int mulGrade1 = 0;
            int mulGrade2 = 0;
 
            Stack<char> stack = new Stack<char>();
 
            string input = Console.ReadLine();
            if (input.Length >= 1 && input.Length <= 30)
            {
                for (int i = 0; i < input.Length; i++)
                {
                    char c = input[i];
 
                    switch(c)
                    {
                        case '(':
                            count1++;
                            stack.Push(c);
                            break;
 
                        case '[':
                            count2++;
                            stack.Push(c);
                            break;
 
                        case ')':
                            if (count1 > 0 && stack.Peek()!='[')
                            {
                                stack.Push(c);
                                count1--;   
                                
                                if(count2 >0)
                                {
                                    mulGrade1 = (count2 * 3)*2*grade1;  
                                }
                                else
                                {
                                    grade1++;
                                }
                            }
                            break;
 
                        case ']':
                            if (count2 > 0 && stack.Peek() != '(')
                            {
                                stack.Push(c);
                                count2--;
                                
                                if (count1 > 0)
                                {
                                    mulGrade2 = (count1 * 2* 3 * grade2;
                                }
                                else
                                {
                                    grade2++;
                                }
                            }
                            break;
                    }
                    
                }
 
                if (count1 != 0 || count2 != 0 || stack.Count==0)
                {
                    Console.WriteLine(0);
                }
 
                Console.WriteLine("( ) : {0}",grade1*2);
                Console.WriteLine("[ ] : {0}",grade2*3);
                Console.WriteLine("겹쳐졌을 때 ([]) : {0}", mulGrade1);
                Console.WriteLine("겹쳐졌을 때 [()] : {0}", mulGrade2);
                Console.WriteLine("토탈 : {0}",mulGrade1+mulGrade2 + grade1 * 2+ grade2 * 3);
 
            }
 
        }
    }
}
 

 

 

 

2504번: 괄호의 값

4개의 기호 ‘(’, ‘)’, ‘[’, ‘]’를 이용해서 만들어지는 괄호열 중에서 올바른 괄호열이란 다음과 같이 정의된다. 한 쌍의 괄호로만 이루어진 ‘()’와 ‘[]’는 올바른 괄호열이다.  만일

www.acmicpc.net

 

'C# > 알고리즘' 카테고리의 다른 글

13. 1967번 트리의 지름  (0) 2020.07.26
12. 1074번 Z (시간 줄임)  (0) 2020.07.11
10. 10845번 큐 (해결)  (0) 2020.06.21
9. 1302번 베스트셀러 (LINQ group by)  (0) 2020.06.07
8. 1343번 폴리오미노  (0) 2020.06.01