ALGORITHM/BOJ

[BOJ] 2458 키 순서

0298 2022. 6. 26. 22:11

https://www.acmicpc.net/problem/2458

 

2458번: 키 순서

1번부터 N번까지 번호가 붙여져 있는 학생들에 대하여 두 학생끼리 키를 비교한 결과의 일부가 주어져 있다. 단, N명의 학생들의 키는 모두 다르다고 가정한다. 예를 들어, 6명의 학생들에 대하여

www.acmicpc.net

2022-06-26


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import java.util.Arrays;
import java.util.Scanner;
 
public class Main2458 {
    public static int N, M;
    public static int[][] dist;
    public static final int INF = Integer.MAX_VALUE;
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        N = sc.nextInt();
        M = sc.nextInt();
 
        dist = new int[N+1][N+1];
 
        for(int[] i : dist) Arrays.fill(i, INF);
 
        for(int i = 0; i < M; i++) {
            dist[sc.nextInt()][sc.nextInt()] = 1;
        }
 
        for(int k = 1; k <= N; k++) {
            for(int i = 1; i <= N; i++) {
                for(int j = 1; j <= N; j++) {
                    if(i == j) continue;
                    if(dist[i][k] != INF && dist[k][j] != INF && dist[i][j] > dist[i][k] + dist[k][j]) {
                        dist[i][j] = dist[i][k] + dist[k][j];
                    }
                }
            }
        }
 
        int answer = 0;
        for(int i = 1; i <= N; i++) {
            int cnt = 0;
            for(int j = 1; j <= N; j++) {
                if(dist[i][j] != INF || dist[j][i] != INF) cnt++;
            }
            if(cnt == N-1) answer++;
        }
 
        System.out.println(answer);
    }
 
cs

 

#문제풀이

 

플로이드와샬 문제이다. 

 

모든 학생 ~ 모든 학생을 다 체크한 후, 어느 한 학생에서 다른 학생들의 키를 비교가 가능한 경우와 다른 학생들에서 어느 한 학생으로 비교가 가능한 경우의 수를 합 했을 때 N-1(본인에서 본인으로 가는 경우 빼기) 인 경우, 키를 알 수 있다고 보면 된다.