下邊兩道題堪稱樹直徑模板!java
import java.util.*; public class Main7 { static int Maxsize=100000; static int map[][]=new int[1001][1001]; static int sum[]=new int[1001]; static boolean vis[]=new boolean[1001]; static int n,max; public static int bfs(int v,int n){ for(int i=1;i<=n;i++) { vis[i]=false; sum[i]=0; } max=0; Queue<Integer>q = new LinkedList<Integer>(); q.offer(v); vis[v]=true; int count =0,k,key=0; while(!q.isEmpty()){ k=q.poll(); for(int i=1;i<=n;i++){ if(map[k][i]!=Maxsize&&vis[i]==false){ vis[i]=true; q.offer(i); sum[i]=sum[k]+map[k][i]; if(sum[i]>max){ max=sum[i]; key=i; } } } // System.out.println(max); } return key; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); for(int i=1;i<=n;i++){ for (int j=1; j<=n; j++) { map[i][j]=Maxsize; } } for(int i=1;i<n;i++){ int a= sc.nextInt(); int b = sc.nextInt(); int w = sc.nextInt(); map[a][b]=map[b][a]=w; } int key; key=bfs(1,n); // System.out.println(max); // System.out.println("fsf"); key=bfs(key,n); System.out.println(max); } }
import java.util.*; public class Main7 { static int Maxsize=100000; static int map[][]=new int[1001][1001]; // static int sum[]=new int[1001]; static boolean vis[]=new boolean[1001]; static int s,n,max,sum; public static void dfs(int start,int n){ if(sum>max){ max=sum; s=start; } for(int i=1;i<=n;i++){ if(!vis[i]&&map[start][i]!=Maxsize){ vis[i]=true; sum+=map[start][i]; dfs(i, n); sum-=map[start][i]; vis[i]=false; } } return ; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); for(int i=1;i<=n;i++){ for (int j=1; j<=n; j++) { map[i][j]=Maxsize; } } for(int i=1;i<n;i++){ int a= sc.nextInt(); int b = sc.nextInt(); int w = sc.nextInt(); map[a][b]=map[b][a]=w; } vis[1]=true; dfs(1, n); Arrays.fill(vis, false); vis[s]=true; dfs(s, n); int price=(10+max+11)*max/2; System.out.println(price); } }