|
| 1 | + ```java |
| 2 | +import java.util.*; |
| 3 | +import java.io.*; |
| 4 | + |
| 5 | +public class Main { |
| 6 | + static class Edge { |
| 7 | + int to, weight; |
| 8 | + public Edge(int to, int weight) { |
| 9 | + this.to = to; |
| 10 | + this.weight = weight; |
| 11 | + } |
| 12 | + } |
| 13 | + static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 14 | + static StringTokenizer st; |
| 15 | + static int N, P; |
| 16 | + static List<Integer>[] adjList; |
| 17 | + static List<Edge> edges; |
| 18 | + static final int MAX = Integer.MAX_VALUE / 2; |
| 19 | + |
| 20 | + public static void main(String[] args) throws Exception { |
| 21 | + st = new StringTokenizer(br.readLine()); |
| 22 | + N = Integer.parseInt(st.nextToken()); |
| 23 | + P = Integer.parseInt(st.nextToken()); |
| 24 | + |
| 25 | + adjList = new List[2 * N + 1]; |
| 26 | + for (int i = 0; i <= 2 * N; i++) adjList[i] = new ArrayList<>(); |
| 27 | + edges = new ArrayList<>(); |
| 28 | + |
| 29 | + for (int i = 1; i <= N; i++) { |
| 30 | + int cap = (i == 1 || i == 2) ? MAX : 1; |
| 31 | + adjList[i].add(edges.size()); |
| 32 | + edges.add(new Edge(i + N, cap)); |
| 33 | + adjList[i + N].add(edges.size()); |
| 34 | + edges.add(new Edge(i, 0)); |
| 35 | + } |
| 36 | + |
| 37 | + for (int i = 0; i < P; i++) { |
| 38 | + st = new StringTokenizer(br.readLine()); |
| 39 | + int from = Integer.parseInt(st.nextToken()); |
| 40 | + int to = Integer.parseInt(st.nextToken()); |
| 41 | + |
| 42 | + adjList[from + N].add(edges.size()); |
| 43 | + edges.add(new Edge(to, MAX)); |
| 44 | + adjList[to].add(edges.size()); |
| 45 | + edges.add(new Edge(from + N, 0)); |
| 46 | + |
| 47 | + adjList[to + N].add(edges.size()); |
| 48 | + edges.add(new Edge(from, MAX)); |
| 49 | + adjList[from].add(edges.size()); |
| 50 | + edges.add(new Edge(to + N, 0)); |
| 51 | + } |
| 52 | + |
| 53 | + int ans = 0; |
| 54 | + while (findPath()) ans++; |
| 55 | + System.out.println(ans); |
| 56 | + } |
| 57 | + |
| 58 | + public static boolean findPath() { |
| 59 | + int[] prev = new int[2 * N + 1]; |
| 60 | + Arrays.fill(prev, -1); |
| 61 | + prev[1] = -2; |
| 62 | + ArrayDeque<Integer> q = new ArrayDeque<>(); |
| 63 | + q.offer(1); |
| 64 | + |
| 65 | + while (!q.isEmpty()) { |
| 66 | + int cur = q.poll(); |
| 67 | + for (int i : adjList[cur]) { |
| 68 | + int to = edges.get(i).to; |
| 69 | + if (prev[to] == -1 && edges.get(i).weight > 0) { |
| 70 | + prev[to] = i; |
| 71 | + if (to == 2) { |
| 72 | + int node = 2; |
| 73 | + while (node != 1) { |
| 74 | + int idx = prev[node]; |
| 75 | + edges.get(idx).weight--; |
| 76 | + edges.get(idx ^ 1).weight++; |
| 77 | + node = edges.get(idx ^ 1).to; |
| 78 | + } |
| 79 | + return true; |
| 80 | + } |
| 81 | + q.offer(to); |
| 82 | + } |
| 83 | + } |
| 84 | + } |
| 85 | + return false; |
| 86 | + } |
| 87 | +} |
| 88 | +``` |
0 commit comments