[백준 11376] 열혈강호 2 (JAVA)

solser12·2021년 11월 30일
0

Algorithm

목록 보기
48/56

문제


풀이


이분 매칭을 이용해서 해결할 수 있습니다. 이분 매칭 방법은 여기서 확인하시면 됩니다. 사람마다 2개의 일을 할 수 있기 때문에 사람은 2배로 복제해 후 이분 매칭을 이용하면 됩니다.

코드


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;

public class Main {

    public static int N, M;
    public static boolean[] visited;
    public static int[] work;
    public static int[][] possible;

    public static void main(String[] args) throws IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        StringTokenizer st = new StringTokenizer(br.readLine());
        N = Integer.parseInt(st.nextToken());
        M = Integer.parseInt(st.nextToken());

        visited = new boolean[M];
        work = new int[M];
        possible = new int[N * 2 + 1][];

        for (int i = 1; i <= N * 2; i += 2) {
            st = new StringTokenizer(br.readLine());
            int num = Integer.parseInt(st.nextToken());
            possible[i] = new int[num];
            possible[i + 1] = new int[num];
            for (int j = 0; j < num; j++) {
                possible[i][j] = Integer.parseInt(st.nextToken()) - 1;
                possible[i + 1][j] = possible[i][j];
            }
        }

        int ans = 0;
        for (int i = 1; i <= N * 2; i++) {
            Arrays.fill(visited, false);
            if (dfs(i)) ans++;
        }

        System.out.println(ans);
        br.close();
    }

    public static boolean dfs(int num) {
        for (int i = 0; i < possible[num].length; i++) {
            if (visited[possible[num][i]]) continue;
            visited[possible[num][i]] = true;

            if (work[possible[num][i]] == 0 || dfs(work[possible[num][i]])) {
                work[possible[num][i]] = num;
                return true;
            }
        }
        return false;
    }
}
profile
더 나은 방법을 생각하고 고민합니다.

0개의 댓글