ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 백준 10845 - 큐 구현
    자료구조와 알고리즘/문제풀기 2023. 4. 5. 11:38

    배열로 큐를 구현하는 문제이다. 

    -큐는 FIFO구조이다.  스택과 반대로 순서를 의미할 때 사용한다.  <-pop 1,2,3 <-push

    - [begin, end)를 이용해서 큐를 배열로 구현할 수 있다.

    - 하나의 큐 연산의 시간복잡도는 1이다.

    public class Main{
        public static void main(String[] args) throws Exception{
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
             myqu m = new myqu();
            int t = Integer.parseInt(br.readLine());
            String input;
            while(t-- >0){
                input = br.readLine();
                if(input.contains("push")){
                    m.push(Integer.valueOf(input.substring(input.indexOf(' ')+1)));
                }else if(input.equals("pop")){
                    System.out.println(m.pop());
                } else if (input.equals("size")) {
                    System.out.println(m.size());
                } else if (input.equals("empty")) {
                    System.out.println(m.empty());
                } else if (input.equals("front")) {
                    System.out.println(m.front());
                } else if (input.equals("back")) {
                    System.out.println(m.back());
                }
            }
        }
    }
    
    class myqu{
        private int[] arr;
        private int begin=0;
        private int end =0;
    
        myqu(){
            this(10000);
        }
        myqu(int n){
            arr = new int[n];
        }
        //push
        public void push(int n){
            if(end>=arr.length)
                ensure();
            arr[end++] = n;
        }
        //fifo
        public int pop(){
            if(empty() ==1 || size() ==0)return -1;
            int rval = arr[begin];
            arr[begin++]=0;
    
            return rval;
        }
        //end - begin
        public int size(){
            return end-begin;
        }
        public int empty(){
            if(size()==0) return 1;
            return 0;
        }
        //맨 앞
        public int front(){
            if(empty()==1||size()==0)return -1;
            return arr[begin];
        }
        //end -1 맨 뒤 
        public int back(){
            if(empty()==1||size()==0)return -1;
            return arr[end-1];
        }
        //크기 자동확보 
        private void ensure(){
            int[] temp = new int[arr.length+6];
            System.arraycopy(arr,0,temp,0,arr.length);
            arr = temp;
        }
    
    }

    '자료구조와 알고리즘 > 문제풀기' 카테고리의 다른 글

    백준 17413 - 단어뒤집기2  (0) 2023.04.05
    백준 1158 - 요세푸스 문제  (0) 2023.04.05
    백준 1406 - 에디터  (0) 2023.04.05
    백준 1874 - 스택수열  (0) 2023.04.04
    백준 9012 - 괄호  (0) 2023.04.04
Designed by Tistory.