[BOJ] 백준 [19581] 두 번째 트리의 지름 JAVA

[BOJ] 백준 [19581] 두 번째 트리의 지름 JAVA

import java.util. * ;

import java.io. * ;

import java.util.stream.Collectors;

public class Main{

static int N;

static boolean [] visit;

static ArrayList < Node > [] list;

public static void main( String [] args) throws IOException {

BufferedReader br = new BufferedReader( new InputStreamReader( System . in ));

N = Integer. parseInt (br.readLine());

list = new ArrayList[N + 1 ];

for ( int i = 1 ;i < = N;i + + )

list[i] = new ArrayList < > ();

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

int [] input = Arrays.stream(br.readLine(). split ( " " )).mapToInt(Integer:: parseInt ).toArray();

list[input[ 0 ]]. add ( new Node(input[ 1 ],input[ 2 ]));

list[input[ 1 ]]. add ( new Node(input[ 0 ],input[ 2 ]));

}

Node node1 = bfs( 1 , 0 );

Node node2 = bfs(node1.node, 0 );

Node result1 = bfs(node1.node, node2.node);

Node result2 = bfs(node2.node, node1.node);

System . out . println (Math.max(result1.weight,result2.weight));

}

static Node bfs( int start, int exNode){

LinkedList < Node > q = new LinkedList < > ();

q. add ( new Node(start, 0 ));

Node retNode = new Node(start, 0 );

visit = new boolean [N + 1 ];

while ( ! q.isEmpty()){

Node cur = q.poll();

visit[cur.node] = true ;

if (cur.weight > retNode.weight & & cur.node ! = exNode)

retNode = cur;

for (Node next : list[cur.node]) {

if ( ! visit[next.node] & & next.node ! = exNode)

q. add ( new Node(next.node,cur.weight + next.weight));

}

}

return retNode;

}

static class Node{

int node;

int weight;

public Node( int node, int weight) {

this .node = node;

this .weight = weight;

}

}

}

from http://katastrophe.tistory.com/46 by ccl(A) rewrite - 2021-10-04 18:26:20