본문 바로가기
문제풀이/코드업

코드업 기초 100제 C++/Java (93~99)

by 혀니쌤1 2023. 12. 22.

목차

     

    코드업 100제 78번부터는 지금까지 배웠던 것을 총합해서 배우는 단계다.

    78번~92번 까지는 배열을 사용 안 해서 풀 수 있지만 (특히 C/C++의 경우) 93번부터는 배열 사용이 필요하다.

    그나저나 코드업 100제지만. 100번에 무슨 일이 있었는지 문제 목록에 없었다, 99번에서 끝나고 말았다. 허허

    93~95번 : 기초 종합 (배열O, 1차원배열)

     

     

    93번~95번 : 이상한 출석번호 부르기 시리즈

    #1093

    #include <iostream>
    using namespace std;
    
    int main() {
      int a;
      cin >> a;
      int arr[23] = {};
      int j;
      for (int i = 0; i < a; i ++){
        cin >> j;
        arr[j-1]++;
      }
      for (int i = 0; i < 23; i ++){
        cout<<arr[i]<<" ";
      }
      return 0;
    }

    import java.util.Scanner;
    
    public class Main {
    
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            int a = sc.nextInt();
            int[] arr = new int[23];
            int ii = 0;
            for (; ii < a; ii++) {
                int num = sc.nextInt();
                arr[num - 1] += 1;
            }
            for (ii = 0; ii < 23; ii++) {
                System.out.print(arr[ii] + " ");
            }
        }
    }

     

    #1094

    #include <iostream>
    using namespace std;
    
    int main() {
      int a;
      cin >> a;
      int arr[a] = {};
      for (int i = 0; i < a; i ++){
        cin >> arr[i];
      }
      for (int i = a-1; i >= 0; i --){
        cout<<arr[i]<<" ";
      }
      return 0;
    }

    import java.util.Scanner;
    
    public class Main {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            int a = sc.nextInt();
            int[] arr = new int[a];
            int ii = 0;
            for (; ii < a; ii++) {
                arr[ii] = sc.nextInt();
            }
            for (ii = a - 1; ii >= 1; ii--) {
                System.out.print(arr[ii] + " ");
            }
            System.out.print(arr[0]);
        }
    }

     

    #1095

    #include <iostream>
    using namespace std;
    
    int main() {
      int a;
      cin >> a;
      int ans = 24;
      int temp;
      for (int i = 0; i < a; i++){
        cin >> temp;
        if (temp<ans){
          ans = temp;
        }
      }
      cout << ans;
      return 0;
    }

    #이제는 BufferReader를 쓸 때. (메모리 시간 차 확인하기)

    이번 문제 같은 경우엔 출력량 보다는 입력량이 많아지는 경우다. 출석 번호가 10000까지도 될 수 있기 때문이다.

    import java.util.Scanner;
    
    public class Main {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            int a = sc.nextInt();
            int[] arr = new int[a];
            int ii = 0;
            for (; ii < a; ii++) {
                arr[ii] = sc.nextInt();
            }
            int m = 24;
            for (ii = 0; ii < a; ii++) {
                if (arr[ii] < m) {
                    m = arr[ii];
                }
            }
            System.out.print(m);
        }
    }

     

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.StringTokenizer;
    
    public class Main {
        public static void main(String[] args) throws IOException {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            int a = Integer.parseInt(br.readLine());
            StringTokenizer st = new StringTokenizer(br.readLine());
            int[] arr = new int[a];
            for (int ii = 0; ii < a; ii++) {
                arr[ii] = Integer.parseInt(st.nextToken());
            }
            int m = 24;
            for (int ii = 0; ii < a; ii++) {
                if (arr[ii] < m) {
                    m = arr[ii];
                }
            }
            System.out.print(m);
        }
    }

     

    아래 사진을 보면 메모리며 시간에서 상당한 차이가 나는 것을 알 수 있다.

     

     

    96~99번 : 기초 종합 (배열O, 2차원배열)

    드디어 2차원 배열이 등장했다!

     

    #1096

    #include <iostream>
    using namespace std;
    
    int main() {
      int a;
      cin >> a;
      int arr[19][19] = {};
      int x, y;
      for (int i = 0; i < a; i++){
        scanf("%d %d",&x,&y);
        arr[x-1][y-1] = 1;
      }
      for (int i =0; i < 19; i ++){
        for (int j = 0; j < 19; j++){
          printf("%d ",arr[i][j]);
        }
        cout << endl;
      }
      return 0;
    }

    import java.io.*;
    import java.util.StringTokenizer;
    
    public class Main {
        static void printboard(int[][] arr) {
            int ii, jj;
            for (ii = 0; ii < 19; ii++) {
                for (jj = 0; jj < 18; jj++) {
                    System.out.print(arr[ii][jj] + " ");
                }
                System.out.println(arr[ii][jj]);
            }
        }
    
        public static void main(String[] args) throws IOException {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
            int a = Integer.parseInt(br.readLine());
            int[][] arr = new int[19][19];
            for (int ii = 0; ii < a; ii++) {
                StringTokenizer st = new StringTokenizer(br.readLine(), " ");
                int y = Integer.valueOf(st.nextToken());
                int x = Integer.valueOf(st.nextToken());
                arr[y - 1][x - 1] = 1;
            }
            Main.printboard(arr);
            br.close();
            bw.flush();
            bw.close();
        }
    }

    BufferReader를 사용할 경우, Scanner와 달리 (예: nextInt()) 공백을 두고 숫자를 끊어 읽을 수 없기 때문에 StringTokenizer사용이 필수다. 자바는 진짜 코드 글자수량이 다른 언어에 비해 너무 많은 것 같다. (손가락근력이 올라가네)

     

     

    #1097

    #include <iostream>
    using namespace std;
    
    int main() {
      int arr[19][19] = {};
      for (int i=0; i<19; i++){
        for (int j=0; j<19; j++){
          cin >> arr[i][j];
        }
      }
      int t, x, y;
      cin >> t;
      for (int i = 0; i < t; i ++){
        scanf("%d %d",&x, &y);
        x--;
        y--;
        for (int j = 0; j < 19; j ++){
          arr[x][j] = !arr[x][j];
          arr[j][y] = !arr[j][y];
        }
      }
      for (int i =0; i < 19; i ++){
        for (int j = 0; j < 19; j++){
          printf("%d ",arr[i][j]);
        }
        cout << endl;
      }
      return 0;
    }

    다시 한 번 Buffer사용 유무 성능차 확인하기

    import java.util.Scanner;
    
    class Main {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            int[][] board = new int[19][19];
            //TODO fill given numbers to your board using scanner:
            for (int i = 0; i < 19; i++) {
                for (int j = 0; j < 19; j++) {
                    board[i][j] = sc.nextInt();
                }
            }
    
            int time = sc.nextInt();
            for (int t = 0; t < time; t++) {
                int r = sc.nextInt() - 1;
                int c = sc.nextInt() - 1;
    
                for (int j = 0; j < 19; j++) {
                    if (board[r][j] == 0) {
                        board[r][j] = 1;
                    } else {
                        board[r][j] = 0;
                    }
                }
    
                for (int i = 0; i < 19; i++) {
                    if (board[i][c] == 0) {
                        board[i][c] = 1;
                    } else {
                        board[i][c] = 0;
                    }
                }
            }
    
            for (int i = 0; i < 19; i++) {
                for (int j = 0; j < 19; j++) {
                    System.out.print(board[i][j] + " ");
                }
                System.out.println();
            }
    
        }
    }

     

    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.util.StringTokenizer;
    
    class Main {
        public static void main(String[] args) throws Exception {
            int[][] board = new int[19][19];
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
            for (int i = 0; i < 19; i++) {
                StringTokenizer st = new StringTokenizer(br.readLine());
                for (int j = 0; j < 19; j++) {
                    int val = Integer.parseInt(st.nextToken());
                    board[i][j] = val;
                }
            }
    
            int n = Integer.parseInt(br.readLine());
            for (int t = 0; t < n; t++) {
                StringTokenizer st = new StringTokenizer(br.readLine());
                int r = Integer.parseInt(st.nextToken()) - 1;
                int c = Integer.parseInt(st.nextToken()) - 1;
                for (int j = 0; j < 19; j++) {
                    if (board[r][j] == 0) {
                        board[r][j] = 1;
                    } else {
                        board[r][j] = 0;
                    }
                }
                for (int i = 0; i < 19; i++) {
                    if (board[i][c] == 0) {
                        board[i][c] = 1;
                    } else {
                        board[i][c] = 0;
                    }
                }
            }
    
            for (int i = 0; i < 19; i++) {
                for (int j = 0; j < 19; j++) {
                    bw.write(board[i][j] + " ");
                }
                bw.write("\n");
            }
            bw.flush();
            bw.close();
        }
    }

     

    19X19 바둑판을 입력받고 후처리한 뒤 출력하는 문제였다.

    데이터 크기가 19X19라서 (100X100도 아니고) 큰 차이는 없을 테지만, 어떻게든 버퍼 사용 유무 성능차를 확인해보고 싶었다. 실험 결과는 아래처럼 나왔다. 스캐너, 시스아웃 VS 버퍼 및 스트링토크나이저 경우다

    ※ 전에 잠시 언급했지만, 버퍼리더를 사용할 경우 공백 끊어읽기가 안되기 때문에 스트링토크나이저 사용이 필수다.

     

     

    #1098

     

    #include <iostream>
    using namespace std;
    
    int main() {
      int n, m;
      cin >> n >> m;
      int arr[n][m] = {};
      int t,l,d,x,y;
      cin >> t;
      for (int i = 0; i < t; i++){
        scanf("%d %d %d %d", &l, &d, &x, &y);
        if (d){
          for (int j = 0; j < l; j ++){
            arr[x-1+j][y-1] = 1;
          }
        }else{
          for (int j = 0; j < l; j ++){
            arr[x-1][y-1+j] = 1;
          }
        }
    
      }
      for (int i = 0; i < n; i ++){
        for (int j = 0 ; j < m; j++){
          cout << arr[i][j] << " ";
        }
        cout << endl;
      }
      return 0;
    }

     


    import java.util.Scanner;
    
    class Main {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            int rsize = sc.nextInt();
            int csize = sc.nextInt();
            int[][] board = new int[rsize][csize];
    
            int n = sc.nextInt(); //number of information
            for (int i = 0; i < n; i++) {
                int l = sc.nextInt();
                int d = sc.nextInt(); // horiz if 0, vert if 1
                int x = sc.nextInt() - 1;
                int y = sc.nextInt() - 1;
    
                if (d == 0) {
                    for (int ind = y; ind < y + l; ind++) {
                        board[x][ind] = 1;
                    }
                } else if (d == 1) {
                    for (int ind = x; ind < x + l; ind++) {
                        board[ind][y] = 1;
                    }
                }
            }
    
            for (int i = 0; i < rsize; i++) {
                for (int j = 0; j < csize; j++) {
                    System.out.print(board[i][j] + " ");
                }
                System.out.println();
            }
        }
    }

     

     

    성실한 개미

    코드업 100제 난이도 최고봉, 정답율 최저(지금 확인해보니 22% ㄷㄷ) 문제다.

    사실 개미는 무조건 오른쪽으로만 간다. (안되면 밑으로 시도) 라고 생각하면 어려운 문제는 아니다. 

     

    여담

    깊게 생각해보지 않고 BFS/DFS처럼 dx = [-1,1,0,0], dy=[0,0,-1,1] 부터 써내려 가는 학생들이 있더라.. (난 아님 ㅠ)

    그나저나 22%  정답율을 백준과 비교해선 안된다. 백준으로 갔다면 성실한 개미는 아마 정답율이 35~40% 정도 나오지 않았을까 싶다. 하지만, 초보자들이 푸는 문제라는 것을 고려해서는 뭐...

     

    #1099

    #include <iostream>
    using namespace std;
    
    int main() {
    	int arr[10][10];
    	for (int i = 0; i < 10; i++){
    		for (int j = 0; j < 10; j++){
    			cin >> arr[i][j];
    		}
    	}
    
    	int x = 1;
    	int y = 1;
    	while (1){
    		//아래 두 케이스면, 더 갈 거 없이 현재 상황 종료
    		if (arr[x][y] == 2){
    			arr[x][y] = 9;
    			break;
    		}
    		if (x==8 && y==8) {
    			arr[x][y] = 9;
    			break;
    		}
    
    		// 오른쪽으로 갈 수 있음
    		if ((y+1)<=8 && arr[x][y+1] != 1){
    			arr[x][y++] = 9;
    			continue;
    		}
    		// 오른쪽으로 못가기 때문에 일단 밑으로 내려감
    		if ((x+1)<=8 && arr[x+1][y] != 1){
    			arr[x++][y] = 9;
    			continue;
    		}
    
    		//위에 두 케이스 안걸리면 아무데도 못간다는 것임. 종료
    		arr[x][y] = 9;
    		break;
    		
    	}
    
    	for (int i = 0; i < 10; i++){
    		for (int j = 0; j < 10; j++){
    			cout << arr[i][j] << " ";
    		}
    		cout << endl;
    	}
    	return 0;
    }

     

     

    예전 글 정리

     

    코드업 기초 100제 C++/Java (1~37)

    1~8번: 기초 출력 스탠다드 인풋 없이 스탠다드 아웃풋만 내는 방식이다. C++의 경우 cout을 사용하였다. (물론 printf도 가능은 하지만) using namespace std;를 외치지 않은 경우, 그냥 cout이 아니라 std::cou

    mylittlenotepad.tistory.com

     

    코드업 기초 100제 C++/Java (38~46, 49~58, 63~64)

    문제집 / C언어 기초 100제 codeup.kr 코드업 기초 100제 C++/Java (1~37) 1~8번: 기초 출력 스탠다드 인풋 없이 스탠다드 아웃풋만 내는 방식이다. C++의 경우 cout을 사용하였다. (물론 printf도 가능은 하지만

    mylittlenotepad.tistory.com

     

    코드업 기초 100제 C++/Java (65~77)

    문제집 / C언어 기초 100제 codeup.kr 코드업 기초 100제 C++/Java (1~37) 1~8번: 기초 출력 스탠다드 인풋 없이 스탠다드 아웃풋만 내는 방식이다. C++의 경우 cout을 사용하였다. (물론 printf도 가능은 하지만

    mylittlenotepad.tistory.com

     

     

    코드업 기초 100제 C++/Java (78~92)

    코드업 78번 부터는 기초 종합이다. 지금까지 배웠던 것을 사용해서 다양한 문제 풀이를 해볼 수 있다. 78번~92번 : 기초 종합 (배열X) #1078 #include int main() { int a; std::cin >> a; int res = 0; for (int i = 2; i b

    mylittlenotepad.tistory.com