Skip to content

Commit f8e2a7b

Browse files
authored
[20260225] BOJ / P4 / 도시 왕복하기 1 / 이강현
1 parent 84aa8fd commit f8e2a7b

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
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 = new ArrayList<>();
18+
static int ans = 0;
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+
adjList = new List[N + 1];
25+
for (int i = 0; i <= N; i++) {
26+
adjList[i] = new ArrayList<>();
27+
}
28+
29+
for (int i = 0; i < P; i++) {
30+
st = new StringTokenizer(br.readLine());
31+
int from = Integer.parseInt(st.nextToken());
32+
int to = Integer.parseInt(st.nextToken());
33+
adjList[from].add(edges.size());
34+
edges.add(new Edge(to, 1));
35+
adjList[to].add(edges.size());
36+
edges.add(new Edge(from, 0));
37+
}
38+
39+
while (findPath()) ans++;
40+
System.out.println(ans);
41+
}
42+
43+
public static boolean findPath() {
44+
int[] prev = new int[N+1];
45+
Arrays.fill(prev, -1);
46+
ArrayDeque<Integer> q = new ArrayDeque<>();
47+
q.offer(1);
48+
prev[1] = 0;
49+
50+
while(!q.isEmpty()){
51+
int cur = q.poll();
52+
if(cur == 2) break;
53+
for(int i : adjList[cur]){
54+
int next = edges.get(i).to;
55+
if(prev[next] == -1 && edges.get(i).weight > 0){
56+
prev[next] = i;
57+
q.offer(next);
58+
}
59+
}
60+
}
61+
62+
if(prev[2] == -1) return false;
63+
64+
int cur = 2;
65+
while(cur != 1){
66+
int idx = prev[cur];
67+
edges.get(idx).weight--;
68+
edges.get(idx ^ 1).weight++;
69+
cur = edges.get(idx ^ 1).to;
70+
}
71+
return true;
72+
}
73+
}
74+
```

0 commit comments

Comments
 (0)