문제 풀이(46)

Youngseon Kim·2023년 10월 27일

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

import java.io.*;
import java.util.*;


public class Main {

    static int N, M;
    static int[][] dist;

    public static void main(String[] args) throws IOException {
        
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    
        StringTokenizer st = new StringTokenizer(br.readLine());

        N = Integer.parseInt(st.nextToken());

        dist = new int[N + 1][N + 1];

        for (int i = 1; i <= N; i++) {
            for (int j = 1; j <= N; j++) {
                if (i == j) {
                    dist[i][j] = 0;
                }else{
                    dist[i][j] = 10000001;
                }
            }
        }

        M = Integer.parseInt(st.nextToken());

        for (int i = 0; i < M; i++) {
            
            st = new StringTokenizer(br.readLine());

            int S = Integer.parseInt(st.nextToken());

            int E = Integer.parseInt(st.nextToken());

            dist[S][E] = 1;
        }

        for (int k = 1; k <= N; k++) {
            for (int i = 1; i <= N; i++) {
                for (int j = 1; j <= N; j++) {
                    if (dist[i][j] > dist[i][k] + dist[k][j]) {
                        dist[i][j] = dist[i][k] + dist[k][j];
                    }
                }
            }
        }

        int res = 0;

        for (int i = 1; i <= N; i++) {
            int cnt = 0;

            for (int j = 1; j <= N; j++) {
                if (dist[i][j] < 10000001 || dist[j][i] < 10000001) {
                    cnt++;
                }
            }

            if (cnt == N ) {
                res++;
            }

        }


        System.out.println(res);

    }

    
}

0개의 댓글