백준 1008 : A/B

C# 2020. 11. 12. 22:58

두 정수 A와 B를 입력받은 다음, A/B를 출력하는 프로그램을 작성하시오.

첫째 줄에 A와 B가 주어진다. (0 < A, B < 10)
첫째 줄에 A/B를 출력한다. 실제 정답과 출력값의 절대오차 또는 상대오차가 10-9 이하이면 정답이다.

:: 성공

: 개선점 : 없음

: Float이 아니라 Double을 써야함

using System;

namespace Print04
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] input = Console.ReadLine().Split(' ');
            Console.WriteLine("{0}", double.Parse(input[0]) / double.Parse(input[1]));
        }
    }
}

'C#' 카테고리의 다른 글

백준 10869 : 사칙연산  (0) 2020.11.14
백준 10998 : A×B  (0) 2020.11.13
백준 10172 : 개 // 성공  (0) 2020.11.07
백준 10171 : 고양이 // 성공  (0) 2020.11.06
백준 1874 : 스택 수열 // 실패  (0) 2020.11.05
블로그 이미지

RIsN

,

백준 10172 : 개 // 성공

C# 2020. 11. 7. 22:03

아래 예제와 같이 개를 출력하시오.

없음.
개를 출력한다.

:: 성공

: 개선점 : 없음

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Print02
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("|\\_/|");
            Console.WriteLine("|q p|   /}");
            Console.WriteLine("( 0 )\"\"\"\\");
            Console.WriteLine("|\"^\"`    |");
            Console.WriteLine("||_/=\\\\__|");
        }
    }
}

'C#' 카테고리의 다른 글

백준 10998 : A×B  (0) 2020.11.13
백준 1008 : A/B  (0) 2020.11.12
백준 10171 : 고양이 // 성공  (0) 2020.11.06
백준 1874 : 스택 수열 // 실패  (0) 2020.11.05
백준 10828 : 스택 // 실패  (0) 2020.11.04
블로그 이미지

RIsN

,

아래 예제와 같이 고양이를 출력하시오.

없음.
고양이를 출력한다.

:: 성공

: 개선점 : 없음

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Print01
{
    class Program
    {
        static void Main(string[] args)
        {
            // :: Print Cat
            Console.WriteLine("\\    /\\");
            Console.WriteLine(" )  ( ')");
            Console.WriteLine("(  /  )");
            Console.WriteLine(" \\(__)|");

            // :: End Program
            //Console.ReadKey();
        }
    }
}

'C#' 카테고리의 다른 글

백준 1008 : A/B  (0) 2020.11.12
백준 10172 : 개 // 성공  (0) 2020.11.07
백준 1874 : 스택 수열 // 실패  (0) 2020.11.05
백준 10828 : 스택 // 실패  (0) 2020.11.04
백준 4949: 균형잡힌 세상 // 성공  (0) 2020.11.01
블로그 이미지

RIsN

,

스택 (stack)은 기본적인 자료구조 중 하나로, 컴퓨터 프로그램을 작성할 때 자주 이용되는 개념이다. 스택은 자료를 넣는 (push) 입구와 자료를 뽑는 (pop) 입구가 같아 제일 나중에 들어간 자료가 제일 먼저 나오는 (LIFO, Last in First out) 특성을 가지고 있다.

1부터 n까지의 수를 스택에 넣었다가 뽑아 늘어놓음으로써, 하나의 수열을 만들 수 있다. 이때, 스택에 push하는 순서는 반드시 오름차순을 지키도록 한다고 하자. 임의의 수열이 주어졌을 때 스택을 이용해 그 수열을 만들 수 있는지 없는지, 있다면 어떤 순서로 push와 pop 연산을 수행해야 하는지를 알아낼 수 있다. 이를 계산하는 프로그램을 작성하라.

첫 줄에 n (1 ≤ n ≤ 100,000)이 주어진다. 둘째 줄부터 n개의 줄에는 수열을 이루는 1이상 n이하의 정수가 하나씩 순서대로 주어진다. 
물론 같은 정수가 두 번 나오는 일은 없다.

:: 실패 이유 : 컴파일 에러

: 개선하지 않는 이유 : 뭐가 문제인지 모르겠다.

: 프로그램 자체는 문제가 말하는 대로 흘러가는데, 정작 컴파일 에러가 계속 뜬다.

: C#은 대체로 전부 문제가 많은 게 아닐까?

: 질문 되면 질문을 올려보고, 안되면 다른 언어로 도전 고려

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace Stack05
{
    class Program
    {
        static void Main(string[] args)
        {
            // :: Initialise
            Stack<int> stack = new Stack<int>();
            List<bool> processChecker = new List<bool>(); 
            Queue<int> input = new Queue<int>();

            // :: Input Command
            int commandSize = Int32.Parse(Console.ReadLine()); // :: CommandSize
            for(int i = 0; i < commandSize; i++)
            {
                // :: Save Input in Queue
                input.Enqueue(Int32.Parse(Console.ReadLine()));
            }

            // :: Start Program
            for (int i = 1; i <= commandSize; i++)
            {
                // :: Push
                stack.Push(i);
                processChecker.Add(true);

                // :: If stack has remains & current stack last value same as input first value;
                while (stack.Count != 0 && stack.Peek() == input.Peek())
                {
                    // :: Pop & input Queue dequeue
                    stack.Pop();
                    processChecker.Add(false);
                    input.Dequeue();
                }
            }
            
            // :: If stack has something : error
            if(stack.Count() != 0)
            {
                Console.WriteLine("NO");
            }
            // :: else print process
            else
            {
                foreach (var itm in processChecker)
                {
                    Console.WriteLine("{0}", itm == true ? "+" : "-");
                }
            }

            // :: End Program
            // Console.ReadKey();
        }
    }
}

'C#' 카테고리의 다른 글

백준 10172 : 개 // 성공  (0) 2020.11.07
백준 10171 : 고양이 // 성공  (0) 2020.11.06
백준 10828 : 스택 // 실패  (0) 2020.11.04
백준 4949: 균형잡힌 세상 // 성공  (0) 2020.11.01
백준 9012 : 괄호 // 성공  (0) 2020.10.31
블로그 이미지

RIsN

,

백준 10828 : 스택 // 실패

C# 2020. 11. 4. 23:39

정수를 저장하는 스택을 구현한 다음, 입력으로 주어지는 명령을 처리하는 프로그램을 작성하시오.

명령은 총 다섯 가지이다.

  • push X: 정수 X를 스택에 넣는 연산이다.
  • pop: 스택에서 가장 위에 있는 정수를 빼고, 그 수를 출력한다. 만약 스택에 들어있는 정수가 없는 경우에는 -1을 출력한다.
  • size: 스택에 들어있는 정수의 개수를 출력한다.
  • empty: 스택이 비어있으면 1, 아니면 0을 출력한다.
  • top: 스택의 가장 위에 있는 정수를 출력한다. 만약 스택에 들어있는 정수가 없는 경우에는 -1을 출력한다.
첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 
둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 
문제에 나와있지 않은 명령이 주어지는 경우는 없다.

:: 실패 이유 : 시간초과

: 개선하지 않는 이유 : 뭐가 문제인지 모르겠다.

: 문제를 못 맞춰서 다른 사람 코드도 볼 수 없고, C# 관련 구글 검색해서 갖다 붙여도 시간초과로 실패함

: 10개 안 풀어서 질문을 올릴 수도 없음, 10개 이상 풀고나서 다음에 확인할 것.

using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace Stack01
{
    class Program
    {
        static void Main(string[] args)
        {
            // :: Initialise
            Stack stack = new Stack();

            // :: Check Command Size
            string input = Console.ReadLine();
            int commandSize = 0;
            try
            {
                commandSize = Int32.Parse(input);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            List<string> inputList = new List<string>();
            // :: Loop Command with Size
            for (int i = 0; i < commandSize; i++)
            {
                string temp = Console.ReadLine();
                inputList.Add(temp);
            }

            foreach (var itm in inputList)
            {
                CheckCommand(itm, stack);
            }

            // :: End Program
            // Console.ReadKey();
        }

        // :: Check Command with String
        public static void CheckCommand(string input, Stack stack)
        {
            string[] command = input.Split(' ');
            switch (command[0])
            {
                case "push":
                    try
                    {
                        int temp = Int32.Parse(command[1]);
                        stack.Push(temp);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }
                    break;
                case "pop":
                    Console.WriteLine(stack.Pop());
                    break;
                case "size":
                    Console.WriteLine(stack.GetSize());
                    break;
                case "empty":
                    Console.WriteLine(stack.CheckEmpty());
                    break;
                case "top":
                    Console.WriteLine(stack.GetTop());
                    break;
            }
        }
    }

    public class Stack
    {
        private List<int> data;
        private int top;

        public Stack()
        {
            data = new List<int>();
            top = -1;
        }

        public void Push(int input)
        {
            data.Add(input);
            top += 1;
        }

        public int Pop()
        {
            if (top < 0)
            {
                return -1;
            }

            int temp = data[top];
            data.RemoveAt(top);
            top -= 1;

            return temp;
        }

        public int GetTop()
        {
            if (top < 0)
                return top;

            return data[top];
        }

        public int GetSize()
        {
            return data.Count();
        }

        public int CheckEmpty()
        {
            return data.Count() > 0 ? 0 : 1;
        }
    }
}

'C#' 카테고리의 다른 글

백준 10171 : 고양이 // 성공  (0) 2020.11.06
백준 1874 : 스택 수열 // 실패  (0) 2020.11.05
백준 4949: 균형잡힌 세상 // 성공  (0) 2020.11.01
백준 9012 : 괄호 // 성공  (0) 2020.10.31
백준 10773 : 제로 // 성공  (0) 2020.10.30
블로그 이미지

RIsN

,

세계는 균형이 잘 잡혀있어야 한다. 양과 음, 빛과 어둠 그리고 왼쪽 괄호와 오른쪽 괄호처럼 말이다.

정민이의 임무는 어떤 문자열이 주어졌을 때, 괄호들의 균형이 잘 맞춰져 있는지 판단하는 프로그램을 짜는 것이다.

문자열에 포함되는 괄호는 소괄호("()") 와 대괄호("[]")로 2종류이고, 문자열이 균형을 이루는 조건은 아래와 같다.

  • 모든 왼쪽 소괄호("(")는 오른쪽 소괄호(")")와만 짝을 이뤄야 한다.
  • 모든 왼쪽 대괄호("[")는 오른쪽 대괄호("]")와만 짝을 이뤄야 한다.
  • 모든 오른쪽 괄호들은 자신과 짝을 이룰 수 있는 왼쪽 괄호가 존재한다.
  • 모든 괄호들의 짝은 1:1 매칭만 가능하다. 즉, 괄호 하나가 둘 이상의 괄호와 짝지어지지 않는다.
  • 짝을 이루는 두 괄호가 있을 때, 그 사이에 있는 문자열도 균형이 잡혀야 한다.

정민이를 도와 문자열이 주어졌을 때 균형잡힌 문자열인지 아닌지를 판단해보자.

하나 또는 여러줄에 걸쳐서 문자열이 주어진다. 각 문자열은 영문 알파벳, 공백, 소괄호("( )") 대괄호("[ ]")등으로 이루어져 있으며, 길이는 100글자보다 작거나 같다.

입력의 종료조건으로 맨 마지막에 점 하나(".")가 들어온다.

:: 성공

: 요점은 좀 더 줄이는 방법이 없을까?

: Dictionary?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Stack04
{
    class Program
    {
        static void Main(string[] args)
        {
            string input = "";
            while(true)
            {
                // :: Input
                input = Console.ReadLine();

                // :: End
                if (input == ".")
                    break;

                // :: Initialise
                Stack<String> bracketA = new Stack<String>();
                bool isError = false; // ::: Check Error

                // :: Check String
                foreach(var itm in input)
                {
                    // :: Input "(" or "[" in Stack
                    if(itm.ToString() == "(" || itm.ToString() == "[")
                    {
                        bracketA.Push(itm.ToString());
                    }
                    // :: Take "(" or "[" when ")" or "]"
                    else if(itm.ToString() == ")" || itm.ToString() == "]")
                    {
                        // :: Stack has something
                        if(bracketA.Count > 0)
                        {
                            // :: When Peek is "("
                            if(bracketA.Peek() == "(")
                            {
                                // :: Matched and Pop it
                                if (itm.ToString() == ")")
                                {
                                    bracketA.Pop();
                                }
                                // :: Not matched
                                else
                                {
                                    isError = true;
                                }
                            }
                            // :: When Peek is "["
                            else if (bracketA.Peek() == "[")
                            {
                                // :: Matched and Pop it
                                if(itm.ToString() == "]")
                                {
                                    bracketA.Pop();
                                }
                                // :: Not matched
                                else
                                {
                                    isError = true;
                                }
                            }
                        }
                        // :: Stack has nothing
                        else
                        {
                            isError = true;
                        }
                    }
                }

                // :: When isError or Stack has remains
                if (bracketA.Count > 0 || isError == true)
                {
                    Console.WriteLine("no");
                }
                // :: Success : Stack has nothing and isError = false
                else
                {
                    Console.WriteLine("yes");
                }
            }
        }
    }
}

'C#' 카테고리의 다른 글

백준 1874 : 스택 수열 // 실패  (0) 2020.11.05
백준 10828 : 스택 // 실패  (0) 2020.11.04
백준 9012 : 괄호 // 성공  (0) 2020.10.31
백준 10773 : 제로 // 성공  (0) 2020.10.30
Study : Quick Sort  (0) 2020.10.26
블로그 이미지

RIsN

,

백준 9012 : 괄호 // 성공

C# 2020. 10. 31. 22:37

괄호 문자열(Parenthesis String, PS)은 두 개의 괄호 기호인 ‘(’ 와 ‘)’ 만으로 구성되어 있는 문자열이다. 그 중에서 괄호의 모양이 바르게 구성된 문자열을 올바른 괄호 문자열(Valid PS, VPS)이라고 부른다. 한 쌍의 괄호 기호로 된 “( )” 문자열은 기본 VPS 이라고 부른다. 만일 x 가 VPS 라면 이것을 하나의 괄호에 넣은 새로운 문자열 “(x)”도 VPS 가 된다. 그리고 두 VPS x 와 y를 접합(concatenation)시킨 새로운 문자열 xy도 VPS 가 된다. 예를 들어 “(())()”와 “((()))” 는 VPS 이지만 “(()(”, “(())()))” , 그리고 “(()” 는 모두 VPS 가 아닌 문자열이다.

여러분은 입력으로 주어진 괄호 문자열이 VPS 인지 아닌지를 판단해서 그 결과를 YES 와 NO 로 나타내어야 한다. 

입력 데이터는 표준 입력을 사용한다. 입력은 T개의 테스트 데이터로 주어진다. 입력의 첫 번째 줄에는 입력 데이터의 수를 나타내는 정수 T가 주어진다. 각 테스트 데이터의 첫째 줄에는 괄호 문자열이 한 줄에 주어진다. 하나의 괄호 문자열의 길이는 2 이상 50 이하이다. 

:: 성공

: 요점은 char 사용을 기피해야 한다는 것

: 첫 코드가 char를 사용해서 확인했는데 양쪽 괄호를 동일하게 인식해서 문제가 생김, toString()을 활용함

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Stack03
{
    class Program
    {
        static void Main(string[] args)
        {
            int commandSize = Int32.Parse(Console.ReadLine()); // :: Command Size

            // :: Rotation Input
            for (int i = 0; i < commandSize; i++)
            {
                // :: Initialise
                Stack<int> stack = new Stack<int>();
                string input = Console.ReadLine();
                string yesNo = "";
                bool isError = false;

                // :: Don't need check, because it's odd
                if(input.Length % 2 != 0)
                {
                    Console.WriteLine("NO");
                    continue;
                }

                foreach(var itm in input)
                {
                    if (itm.ToString() == "(")
                    {
                        stack.Push(1);
                    } else
                    {
                        if(stack.Count > 0)
                        {
                            stack.Pop();
                        } else
                        {
                            isError = true;
                        }
                    }
                }

                if(isError)
                {
                    Console.WriteLine("NO");
                } else
                {
                    Console.WriteLine("{0}", stack.Count > 0 ? "NO" : "YES");
                }
            }
        }
    }
}

'C#' 카테고리의 다른 글

백준 10828 : 스택 // 실패  (0) 2020.11.04
백준 4949: 균형잡힌 세상 // 성공  (0) 2020.11.01
백준 10773 : 제로 // 성공  (0) 2020.10.30
Study : Quick Sort  (0) 2020.10.26
숫자 출력 시 1000단위 구분기호 추가하는 법  (0) 2020.09.24
블로그 이미지

RIsN

,

백준 10773 : 제로 // 성공

C# 2020. 10. 30. 22:22

나코더 기장 재민이는 동아리 회식을 준비하기 위해서 장부를 관리하는 중이다.

재현이는 재민이를 도와서 돈을 관리하는 중인데, 애석하게도 항상 정신없는 재현이는 돈을 실수로 잘못 부르는 사고를 치기 일쑤였다.

재현이는 잘못된 수를 부를 때마다 0을 외쳐서, 가장 최근에 재민이가 쓴 수를 지우게 시킨다.

재민이는 이렇게 모든 수를 받아 적은 후 그 수의 합을 알고 싶어 한다. 재민이를 도와주자!

첫 번째 줄에 정수 K가 주어진다. (1 ≤ K ≤ 100,000)

이후 K개의 줄에 정수가 1개씩 주어진다. 정수는 0에서 1,000,000 사이의 값을 가지며, 정수가 "0" 일 경우에는 가장 최근에 쓴 수를 지우고, 아닐 경우 해당 수를 쓴다.

정수가 "0"일 경우에 지울 수 있는 수가 있음을 보장할 수 있다.

:: 성공

: 이전과 달리 그냥 스택을 사용

: 스택 기능 중에 SUM이 있길래 그대로 사용, 꽤 짧다.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Stack02
{
    class Program
    {
        static void Main(string[] args)
        {
            string input = Console.ReadLine();
            Stack<int> stack = new Stack<int>();

            int commandSize = Int32.Parse(input);
            for(int i = 0; i < commandSize; i++)
            {
                input = Console.ReadLine();
                int inputParse = Int32.Parse(input);

                if (inputParse == 0)
                {
                    stack.Pop();
                } else
                {
                    stack.Push(inputParse);
                }
            }

            Console.WriteLine(stack.Sum());
        }
    }
}

 

'C#' 카테고리의 다른 글

백준 10828 : 스택 // 실패  (0) 2020.11.04
백준 4949: 균형잡힌 세상 // 성공  (0) 2020.11.01
백준 9012 : 괄호 // 성공  (0) 2020.10.31
Study : Quick Sort  (0) 2020.10.26
숫자 출력 시 1000단위 구분기호 추가하는 법  (0) 2020.09.24
블로그 이미지

RIsN

,

Study : Quick Sort

C# 2020. 10. 26. 22:56

<퀵 정렬>

  :: 간략 정보

    - 가장 빠른 정렬 알고리즘

    - 자기 자신을 불러 쪼개서 정렬을 함

    - 수학적으로 이해해야 해서 더럽게 어려움

  :: 구조

    - 완벽하게 이해 못해서 못쓰겠음

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Study33_QuickSort
{
    public class App
    {
        public App()
        {
            // :: Testing Value
            int[] arr = new int[10] { 4, 8, 7, 6, 9, 1, 3, 2, 0, 5 };
            this.ShowArray(arr);

            this.QuickSort(arr, 0, arr.Length - 1);

            this.ShowArray(arr);

        }

        public void QuickSort(int[] arr, int indexStart, int indexEnd)
        {
            // :: Null Break;
            if (indexStart >= arr.Length)
                return;

            int target = arr[indexStart];
            int left = indexStart + 1;
            int right = indexEnd;

            while(left <= right)
            {
                // :: When target is bigger than Left Value : Skip
                while(arr[left] < target)
                {
                    left += 1;

                    // :: Null Break;
                    if (left >= arr.Length)
                        break;
                }
                // :: When target is smaller than Right Value : Skip
                while (arr[right] > target)
                {
                    right -= 1;

                    // :: Null Break;
                    if (right < 0)
                        break;
                }

                // :: I didn't understand this yet.
                if(left <= right)
                {
                    SwapArray(arr, left, right);
                }
            }            

            // :: I didn't understand this yet.
            // :: Until Start index is same End index : It means dividing is one now.
            if(indexStart < indexEnd)
            {
                // :: Swap target and Right Value
                SwapArray(arr, indexStart, right);

                QuickSort(arr, indexStart, right - 1); // :: Front
                QuickSort(arr, right + 1, indexEnd); // :: End
            }

            return;
        }

        public void SwapArray(int[] arr, int a, int b)
        {
            int temp = arr[a];
            arr[a] = arr[b];
            arr[b] = temp;
        }

        public void ShowArray(int[] arr)
        {
            foreach(var itm in arr)
            {
                Console.Write("[{0}]", itm);
            }
            Console.WriteLine("");
        }

        public void Today()
        {
            DateTime today = new DateTime(2020, 10, 26);
            Console.WriteLine(today.ToString("yyyy-MM-dd") + " : THINK");
        }
    }
}

 

글 업데이트 : 2020-10-26

 

참고 사이트 :

blockdmask.tistory.com/177

블로그 이미지

RIsN

,

변환 {0} => {0:#,0}

Console.WriteLine("{0:#,0}cc, {1}km/l", cc, kmLitre);

 

www.atmarkit.co.jp/ait/articles/0707/19/news143.html

'C#' 카테고리의 다른 글

백준 10828 : 스택 // 실패  (0) 2020.11.04
백준 4949: 균형잡힌 세상 // 성공  (0) 2020.11.01
백준 9012 : 괄호 // 성공  (0) 2020.10.31
백준 10773 : 제로 // 성공  (0) 2020.10.30
Study : Quick Sort  (0) 2020.10.26
블로그 이미지

RIsN

,