java 最大匹配_AcWing 861. 二分图的最大匹配-java-关键处注释

import java.io.*;

import java.util.Arrays;

class Main {

static int n1, n2, m;

//邻接表形式存放左边到右边的边

static int idx;

static int[] h = new int[510];

static int[] e = new int[100010];

static int[] ne = new int[100010];

static {

Arrays.fill(h,-1);

}

//记录当前遍历的左边点对应的右边点是否已搜索过

static boolean[] flag = new boolean[510];

//记录右边点匹配的左边点

static int[] match = new int[510];

static void insert(int a, int b) {

e[idx] = b;

ne[idx] = h[a];

h[a] = idx++;

}

static boolean find(int left) {

for (int i = h[left]; i != -1; i = ne[i]) {

int right = e[i];

//没搜过,进入搜索,标记为已搜索避免递归中重复搜到导致死循环

if (!flag[right]) {

flag[right] = true;

if (match[right] == 0 || find(match[right])) {

match[right] = left;

return true;

}

}

}

return false;

}

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

InputStreamReader isr = new InputStreamReader(System.in);

BufferedReader in = new BufferedReader(isr);

String[] strs = in.readLine().split(" ");

n1 = Integer.parseInt(strs[0]);

n2 = Integer.parseInt(strs[1]);

m = Integer.parseInt(strs[2]);

for (int i = 1; i<=m; i++) {

strs = in.readLine().split(" ");

int a = Integer.parseInt(strs[0]);

int b = Integer.parseInt(strs[1]);

insert(a,b);

}

in.close();

isr.close();

OutputStreamWriter osw = new OutputStreamWriter(System.out);

BufferedWriter out = new BufferedWriter(osw);

int res = 0;

for (int i = 1; i<=n1; i++) {

//关键:对于每个左边点,遍历所有相关的右边点前,先将flag数组清空

Arrays.fill(flag, false);

if (find(i)) res++;

}

out.write(String.valueOf(res));

out.flush();

out.close();

osw.close();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值