Skip to content

Commit c597cae

Browse files
authored
Merge pull request #2041 from AlgorithmWithGod/LiiNi-coder
[20260324] BOJ / G3 / 역사 / 이인희
2 parents cb15747 + 347f16f commit c597cae

1 file changed

Lines changed: 74 additions & 0 deletions

File tree

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+
public class Main{
5+
/*
6+
* 순서 그래프 생성
7+
* 간선 최적화 안하고 그냥 바로 최단거리 알고리즘 돌림
8+
*
9+
* */
10+
private static List<List<Integer>> Graph;
11+
private static int N, M;
12+
private static int MAX = Integer.MAX_VALUE / 2;
13+
public static void main(String[] args) throws IOException{
14+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
15+
StringTokenizer st = new StringTokenizer(br.readLine());
16+
N = Integer.parseInt(st.nextToken());
17+
M = Integer.parseInt(st.nextToken());
18+
Graph = new ArrayList<>();
19+
for(int i = 0; i < N; i++) Graph.add(new ArrayList<>());
20+
for(int i = 0; i < M; i++){
21+
st = new StringTokenizer(br.readLine());
22+
int s = Integer.parseInt(st.nextToken()) - 1;
23+
int e = Integer.parseInt(st.nextToken()) - 1;
24+
25+
Graph.get(s).add(e);
26+
}
27+
28+
//인접리스트 -> 인접행렬
29+
int[][] dists = new int[N][N];
30+
for(int r = 0; r < N; r++)
31+
for(int c = 0; c < N; c++)
32+
dists[r][c] = MAX;
33+
for(int s = 0; s < N; s++){
34+
for(int e : Graph.get(s)){
35+
dists[s][e] = 1;
36+
}
37+
}
38+
for(int i = 0; i < N; i++)
39+
dists[i][i] = 0;
40+
41+
//플로이드워셜
42+
for(int k = 0; k < N; k++)
43+
for(int s = 0; s < N; s++)
44+
for(int e = 0; e < N; e++){
45+
int nw = dists[s][k] + dists[k][e];
46+
if(nw < dists[s][e])
47+
dists[s][e] = nw;
48+
}
49+
50+
// for(int[] row : dists)
51+
// System.out.println(Arrays.toString(row));
52+
int query = Integer.parseInt(br.readLine());
53+
for(int i = 0; i < query; i++){
54+
st = new StringTokenizer(br.readLine());
55+
int l = Integer.parseInt(st.nextToken()) - 1;
56+
int r = Integer.parseInt(st.nextToken()) -1;
57+
58+
boolean lr = (dists[l][r] > 0 && dists[l][r] < MAX);
59+
boolean rl = (dists[r][l] > 0 && dists[r][l] < MAX );
60+
// System.out.println(lr + ", " + rl);
61+
String answer;
62+
if(lr)
63+
answer = "-1";
64+
else if(rl)
65+
answer = "1";
66+
else
67+
answer = "0";
68+
System.out.println(answer);
69+
}
70+
71+
br.close();
72+
}
73+
}
74+
```

0 commit comments

Comments
 (0)