求树的最大直径
作者:互联网
求树直径原理:以任意点w开始,先做一次DFS(BFS),找到最远点v,然后以此点v,进行一次DFS(BFS),找到最远点u,u到v就是树的直径,记做d(u,v)。
下边两道题堪称树直径模板!
TOJ 3517 The longest athletic track
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); } }
大臣的旅费(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 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); } }
标签:最大,int,max,sum,static,求树,new,直径,1001 来源: https://www.cnblogs.com/ls-pankong/p/10542564.html