File tree Expand file tree Collapse file tree 1 file changed +70
-0
lines changed
Expand file tree Collapse file tree 1 file changed +70
-0
lines changed Original file line number Diff line number Diff line change 1+ ``` java
2+ import java.util.* ;
3+ import java.io.* ;
4+
5+ public class boj1240 {
6+ static BufferedReader br = new BufferedReader (new InputStreamReader (System . in));
7+ static StringTokenizer st;
8+ static void nextLine () throws Exception {st = new StringTokenizer (br .readLine ());}
9+ static int nextInt() {return Integer . parseInt(st. nextToken());}
10+ static ArrayList<Node > [] map;
11+ static boolean [] visit;
12+ static int n;
13+ static int max;
14+
15+ public static void main(String [] args) throws Exception {
16+ nextLine();
17+ n = nextInt();
18+ int m = nextInt();
19+ map = new ArrayList [n];
20+ visit = new boolean [n];
21+
22+ for (int i = 0 ; i < n; i++ ) {
23+ map[i] = new ArrayList<> ();
24+ }
25+
26+ for (int i = 0 ; i < n - 1 ; i++ ) {
27+ nextLine();
28+ int a = nextInt() - 1 ;
29+ int b = nextInt() - 1 ;
30+ int d = nextInt();
31+ map[a]. add(new Node (b, d));
32+ map[b]. add(new Node (a, d));
33+ }
34+
35+ for (int i = 0 ; i < m; i++ ) {
36+ nextLine();
37+ int a = nextInt() - 1 ;
38+ int b = nextInt() - 1 ;
39+ dfs(a, b, 0 );
40+ System . out. println(max);
41+ max = 0 ;
42+ visit = new boolean [n];
43+ }
44+ }
45+
46+ static void dfs(int start, int end, int dist) {
47+ if (start == end) {
48+ max = dist;
49+ return ;
50+ }
51+
52+ visit[start] = true ;
53+ for (int i = 0 ; i < map[start]. size(); i++ ) {
54+ if (! visit[map[start]. get(i). next]) {
55+ dfs(map[start]. get(i). next, end, dist + map[start]. get(i). dist);
56+ }
57+ }
58+ }
59+ }
60+
61+ class Node {
62+ int next;
63+ int dist;
64+
65+ public Node (int next , int dist ) {
66+ this . next = next;
67+ this . dist = dist;
68+ }
69+ }
70+ ```
You can’t perform that action at this time.
0 commit comments