The milk business is booming! Farmer John's milk processing factory consists of processing stations, conveniently numbered (), and walkways, each connecting some pair of stations. (Walkways are expensive, so Farmer John has elected to use the minimum number of walkways so that one can eventually reach any station starting from any other station).
To try and improve efficiency, Farmer John installs a conveyor belt in each of its walkways. Unfortunately, he realizes too late that each conveyor belt only moves one way, so now travel along each walkway is only possible in a single direction! Now, it is no longer the case that one can travel from any station to any other station.
However, Farmer John thinks that all may not be lost, so long as there is at least one station such that one can eventually travel to station from every other station. Note that traveling to station from another arbitrary station may involve traveling through intermediate stations between and . Please help Farmer John figure out if such a station exists.
The first line contains an integer , the number of processing stations. Each of the next lines contains two space-separated integers and with and . This indicates that there is a conveyor belt that moves from station to station , allowing travel only in the direction from to .
If there exists a station such that one can walk to station from any other station, then output the minimal such . Otherwise, output .
- 플로이드 와샬 알고리즘을 사용하였다.
- 이중 반복문으로 통해 구한다.
(밖 반복문 : 해당 station)
(안 반복문 : 해당 station에 들어오는 station)
해당 station 으로 들어 올 수 있는 개수를 구해 N-1일 경우 해당 station을 answer에 저장 후 종료한다.
-> N-1일 경우 종료하는 이유 :then output the minimal such (해당하는 i가 제일 작아야하기 때문)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
static int N;
static int[][] graph;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
N = Integer.parseInt(br.readLine());
graph = new int[N+1][N+1];
StringTokenizer st;
for(int i=0; i<N-1; i++){
st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
graph[a][b] = 1;
}
for(int k=1; k<=N; k++){
for(int i=1; i<=N; i++){
for(int j=1; j<=N; j++){
if(graph[i][k]==1 && graph[k][j]==1){
graph[i][j] = 1;
}
}
}
}
int answer = -1;
for(int i=1; i<=N; i++){
int count = 0;
for(int j=1; j<=N; j++){
if(graph[j][i]==1){
count++;
}
}
if(count == N-1){
answer = i;
break;
}
}
System.out.println(answer);
}
}
문제가 영어로 되어있어서 당황했다.... 당황하지 않고 영어 공부를 좀 해야겠다..