Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weโ€™ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

10-mong3125 #35

Merged
merged 1 commit into from
Mar 18, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package DFS;

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

public class BOJ1167_ํŠธ๋ฆฌ์˜์ง€๋ฆ„๊ตฌํ•˜๊ธฐ {

static ArrayList<Edge>[] edges;
static boolean[] visited;
static int max;
static int farthest;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int V = Integer.parseInt(br.readLine());
edges = new ArrayList[V + 1];
for (int i = 0; i < V + 1; i++) {
edges[i] = new ArrayList<>();
}

for (int i = 0; i < V; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());

while (true) {
int node = Integer.parseInt(st.nextToken());
if (node == -1) break;

int cost = Integer.parseInt(st.nextToken());
edges[a].add(new Edge(node, cost));
}
}

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

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

System.out.println(max);
}

public static void dfs(int node, int cost) {
visited[node] = true;
if (cost > max) {
farthest = node;
max = cost;
}

for (Edge edge : edges[node]) {
if (!visited[edge.node]) {
dfs(edge.node, cost + edge.cost);
}
}
}

static class Edge {
int node;
int cost;

public Edge(int node, int cost) {
this.node = node;
this.cost = cost;
}
}
}