[랜덤 마라톤] CARDS(3280)

lhs's avatar
Dec 18, 2024
[랜덤 마라톤] CARDS(3280)
notion image
notion image

1. 문제 풀이 아이디어

  • 입력으로 주어지는 정보를 2차원 배열에 저장하고, 특정 조건에 따라 교집합을 계산하여 문제를 해결한다.

2. 나의 정답 코드

public class Main { public static void main(String[] args) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(bufferedReader.readLine()); int d = Integer.parseInt(bufferedReader.readLine()); int[][] c = new int[n / 3][3]; Set<Integer> set = null; for (int i = 0; i < n; i++) { c[i / 3][i % 3] = i + 1; } for (int i = 0; i < d; i++) { String s = bufferedReader.readLine(); Set<Integer> temp = new HashSet<>(); int k = 2; if (s.equals("first")) { k = 0; } else if (s.equals("second")) { k = 1; } for (int j = 0; j < n / 3; j++) { temp.add(c[j][k]); } if (i == 0) set = temp; else set.retainAll(temp); int[][] c2 = new int[n / 3][3]; int index = 0; for (int j = 0; j < 3; j++) { for (int l = 0; l < n / 3; l++) { c2[index / 3][index % 3] = c[l][j]; index++; } } c = c2; } for (int i : set) { System.out.print(i + " "); } bufferedReader.close(); } }

3. 정리

  • 데이터를 3개의 열로 나누어 초기화한 뒤, 각 조건에 따라 해당 열의 값을 Set에 추가한다.
  • 첫 번째 조건에서는 초기 Set을 생성하고, 이후 조건에서는 retainAll()을 사용해 교집합을 유지한다.
  • 데이터 순환을 통해 c 배열을 갱신하며 새로운 배열 상태를 유지한다.
  • 최종적으로 조건을 만족하는 Set의 값을 순서대로 출력해 문제를 해결했다.
Share article

LHS's Study Space