-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBarnAssign_2188.java
More file actions
64 lines (61 loc) · 2.75 KB
/
BarnAssign_2188.java
File metadata and controls
64 lines (61 loc) · 2.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import java.io.*;
import java.util.*;
public class BarnAssign_2188{
static int N, M;
static boolean[] visited;
static int[][] edges;
static int[] aMatch, bMatch;
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
edges = new int[N][M];
for(int cowNum=0; cowNum<N; cowNum++){
st = new StringTokenizer(br.readLine());
int barnSize = Integer.parseInt(st.nextToken());
for(int i=0; i<barnSize; i++){
int barnNum = Integer.parseInt(st.nextToken())-1;
edges[cowNum][barnNum] = 1;
}
}
System.out.println(bipartiteMatching());
}
// ���� A�� ���� a���� B�� ��Ī���� ���� �������� ���� ��θ� ã�� �Լ�
public static boolean dfs(int a){
if(visited[a]) return false; // ��湮 cut. ��Ī ���� �� �� ������ �ڵ尡 ��� �ۿ��ϴ��� ����
visited[a] = true;
for(int b=0; b<M; ++b){
if(edges[a][b]==1){
//b�� ���� ������ ���� ��
if(bMatch[b] == -1){
aMatch[a] = b;
bMatch[b] = a;
return true;
}
//b�� �̹� ��Ī�Ǿ� �ִٸ� bMatch[b]�������� ������ ��θ� ã�´�. ã���� ��� ��� ȣ���� �κп��� ��θ� �����Ѵ�.
if(dfs(bMatch[b])){
//dfs ȣ��(���ȣ��)���� ��θ� ���������� b�� ����� ������ �����Ƿ� �������ش�.
aMatch[a] = b;
bMatch[b] = a;
return true;
}
}
}
return false;
}
public static int bipartiteMatching(){
aMatch = new int[N];
bMatch = new int[M];
Arrays.fill(aMatch, -1);
Arrays.fill(bMatch, -1);
int size = 0;
for(int start = 0; start < N; start++){
visited = new boolean[N];
//�������, �� ��Ī�� ã�� ��� 1�� ������ ������Ų��.
//���� ��� � ������ +1?
if(dfs(start)) ++size;
}
return size;
}
}