Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 88 additions & 0 deletions lkhyun/202602/26 BOJ P3 도시 왕복하기 2.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
```java
import java.util.*;
import java.io.*;

public class Main {
static class Edge {
int to, weight;
public Edge(int to, int weight) {
this.to = to;
this.weight = weight;
}
}
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer st;
static int N, P;
static List<Integer>[] adjList;
static List<Edge> edges;
static final int MAX = Integer.MAX_VALUE / 2;

public static void main(String[] args) throws Exception {
st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
P = Integer.parseInt(st.nextToken());

adjList = new List[2 * N + 1];
for (int i = 0; i <= 2 * N; i++) adjList[i] = new ArrayList<>();
edges = new ArrayList<>();

for (int i = 1; i <= N; i++) {
int cap = (i == 1 || i == 2) ? MAX : 1;
adjList[i].add(edges.size());
edges.add(new Edge(i + N, cap));
adjList[i + N].add(edges.size());
edges.add(new Edge(i, 0));
}

for (int i = 0; i < P; i++) {
st = new StringTokenizer(br.readLine());
int from = Integer.parseInt(st.nextToken());
int to = Integer.parseInt(st.nextToken());

adjList[from + N].add(edges.size());
edges.add(new Edge(to, MAX));
adjList[to].add(edges.size());
edges.add(new Edge(from + N, 0));

adjList[to + N].add(edges.size());
edges.add(new Edge(from, MAX));
adjList[from].add(edges.size());
edges.add(new Edge(to + N, 0));
}

int ans = 0;
while (findPath()) ans++;
System.out.println(ans);
}

public static boolean findPath() {
int[] prev = new int[2 * N + 1];
Arrays.fill(prev, -1);
prev[1] = -2;
ArrayDeque<Integer> q = new ArrayDeque<>();
q.offer(1);

while (!q.isEmpty()) {
int cur = q.poll();
for (int i : adjList[cur]) {
int to = edges.get(i).to;
if (prev[to] == -1 && edges.get(i).weight > 0) {
prev[to] = i;
if (to == 2) {
int node = 2;
while (node != 1) {
int idx = prev[node];
edges.get(idx).weight--;
edges.get(idx ^ 1).weight++;
node = edges.get(idx ^ 1).to;
}
return true;
}
q.offer(to);
}
}
}
return false;
}
}
```