AcWing 1394. 完美牛棚
原题链接
中等
完美牛棚 - Java版本 - 使用了BufferedReader的更进一步封装
import java.util.*;
import java.io.*;
public class Main{
static StreamTokenizer st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
static PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out));
static int nextInt() throws Exception{
st.nextToken();
return (int)st.nval;
}
static int[] h, e, ne, match;
static boolean[] visited;
static int idx;
public static void main(String[] args) throws Exception{
int n = nextInt();
int m = nextInt();
int res = 0;
h = new int[n + 1];
e = new int[n * m + 1];
ne = new int[n * m + 1];
match = new int[n + 1];
visited = new boolean[m + 1];
Arrays.fill(h , -1);
for(int i = 1; i <= n; i ++){
int s = nextInt();
while (s -- > 0){
int target=nextInt();
add(i,target);
}
}
for(int i = 1; i <= n; i ++){
Arrays.fill(visited , false);
if(find(i)) res ++;
}
pw.print(res);
pw.flush();
}
static boolean find(int u){
for(int i = h[u]; i != -1; i = ne[i]){
int v = e[i];
if(!visited[v]){
visited[v] = true;
if(match[v] == 0 || find(match[v])){
match[v] = u;
return true;
}
}
}
return false;
}
static void add(int a, int b){
e[idx] = b;
ne[idx] = h[a];
h[a] = idx ++;
}
}