Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.Scanner;
- public class Main {
- static ArrayList<Integer>[] graph;
- static int[] d;
- static boolean[] visited;
- static int ans = 0;
- static void dfs(int v) {
- visited[v] = true;
- int max1 = -1;
- int max2 = -1;
- for (int i = 0; i < graph[v].size(); i++) {
- int to = graph[v].get(i);
- if (!visited[to]) {
- dfs(to);
- if (d[to] >= max1) {
- int t = max1;
- max1 = d[to];
- max2 = t;
- } else if (d[to] > max2) {
- max2 = d[to];
- }
- }
- }
- ans = Math.max(ans, (max1 + max2 + 2));
- d[v] = max1 + 1;
- }
- public static void main(String[] args) {
- Scanner s = new Scanner(System.in);
- int n = s.nextInt();
- graph = new ArrayList[n];
- for (int i = 0; i < n; i++) {
- graph[i] = new ArrayList<Integer>();
- }
- d = new int[n];
- visited = new boolean[n];
- for (int i = 0; i < n - 1; i++) {
- int x = s.nextInt() - 1;
- int y = s.nextInt() - 1;
- graph[x].add(y);
- graph[y].add(x);
- }
- dfs(0);
- System.out.println(ans);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement