๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

Algorithm

[Algorithm/Java][๋ฐฑ์ค€] 1167 ํŠธ๋ฆฌ์˜ ์ง€๋ฆ„

๋ฐ˜์‘ํ˜•

[BOJ] 1167 ํŠธ๋ฆฌ์˜ ์ง€๋ฆ„

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

๋ฌธ์ œ ์ ‘๊ทผ

์ด ๋ฌธ์ œ๋Š” ์•„๋ž˜ ๋ฌธ์ œ์™€ ๊ฑฐ์˜ ๋˜‘๊ฐ™์€ ๋ฌธ์ œ์ด๋‹ค. ํŠธ๋ฆฌ๋ฅผ ์ž…๋ ฅํ•ด์ฃผ๋Š” ๋ฐฉ์‹๋งŒ ๋‹ค๋ฅด๊ณ  ์•Œ๊ณ ๋ฆฌ์ฆ˜์€ ๋˜‘๊ฐ™์€ ๋ฌธ์ œ์—ฌ์„œ ์‰ฝ๊ฒŒ ํ’€ ์ˆ˜ ์žˆ์—ˆ๋‹ค.
1967 ํŠธ๋ฆฌ์˜ ์ง€๋ฆ„

Code

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;

public class BOJ1167 {
    static class Node{
        int to;
        int dist;
        public Node(int to, int dist) {
            this.to = to;
            this.dist = dist;
        }
    }
    static int V;
    static ArrayList<Node>[] graph;
    static boolean[] visited;
    static int max = 0, maxIndex = 0;
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        V = Integer.parseInt(br.readLine());
        graph = new ArrayList[V+1];
        for(int i = 0; i<=V; i++){
            graph[i] = new ArrayList<>();
        }
        for(int i = 1 ; i<=V; i++){
            StringTokenizer st = new StringTokenizer(br.readLine(), " ");
            int idx = Integer.parseInt(st.nextToken());
            while(true){
                int to = Integer.parseInt(st.nextToken());
                if(to == -1){
                    break;
                }
                int dist = Integer.parseInt(st.nextToken());
                graph[idx].add(new Node(to,dist));
            }
        }
        visited = new boolean[V+1];
        dfs(1,0);

        visited = new boolean[V+1];
        dfs(maxIndex,0);

        System.out.println(max);
    }

    /**
     * dfs ํƒ์ƒ‰์„ ํ†ตํ•ด์„œ ๊ฐ€์žฅ ๋ฉ€๋ฆฌ ์žˆ๋Š” ๋…ธ๋“œ์™€์˜ ๊ฒฝ๋กœ ๊ธธ์ด์™€ ๊ทธ ๋…ธ๋“œ์˜ ์ธ๋ฑ์Šค๋ฅผ ๊ตฌํ•˜๋Š” ํ•จ์ˆ˜.
     * @param i ํƒ์ƒ‰ํ•˜๋ ค๋Š” ๋…ธ๋“œ ์ธ๋ฑ์Šค
     * @param dist ์ง€๊ธˆ๊นŒ์ง€์˜ ๊ฒฝ๋กœ์˜ ๊ธธ์ด
     */
    static void dfs(int i, int dist){
        if(dist > max){
            max = dist;
            maxIndex = i;
        }
        visited[i] = true;
        for(Node n : graph[i]){
            if(!visited[n.to]){
                dfs(n.to,dist+n.dist);
            }
        }
    }
}

์–ด๋ ค์› ๋˜ ์  / ๋ฐฐ์šด ์  / ๋Š๋‚€ ์ 

๋ฐ”๋กœ ์–ด์ œ ํ’€์—ˆ๋˜ ๋ฌธ์ œ์™€ ๊ฑฐ์˜ ๋˜‘๊ฐ™์€ ๋ฌธ์ œ์—ฌ์„œ ์‰ฝ๊ฒŒ ํ’€ ์ˆ˜ ์žˆ์—ˆ๋‹ค.
๊ทธ๋Ÿฐ๋ฐ ๋‹ค์‹œ ์ฝ”๋“œ๋ฅผ ์งœ๋‹ค๋ณด๋‹ˆ๊นŒ ๋ณ€์ˆ˜๋ช…์ด๋‚˜ ์•ฝ๊ฐ„์˜ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ๋” ๋ณด๊ธฐ์ข‹๊ฒŒ ๋ฐ”๊พธ์—ˆ๋‹ค.(๋‚˜๋ฆ„๋Œ€๋กœ ๋ฆฌํŒฉํ† ๋ง)

๋ฐ˜์‘ํ˜•