Codeforces #14(div2) D "Two Paths"
問題:http://codeforces.com/contest/14/problem/D
他の人のコードを書き写してみた.
どうやら全域木になっているようなので,任意のエッジを切断したあとの
エッジの端点を含む木における最長の長さ(木の深さかリーフ同士における
最長の長さ)を求めていると自分なりに解釈してみた.
import java.util.*; public class D_TwoPaths { public static void main(String[] z) { Scanner s = new Scanner(System.in); int n=s.nextInt(); edges = new ArrayList<List<Integer>>(); for(int i=0;i<n;++i){ edges.add(new ArrayList<Integer>()); } for(;n-->1;){ int u=s.nextInt()-1,v=s.nextInt()-1; edges.get(u).add(v); edges.get(v).add(u); } int res=0; for(int i=0;i<edges.size();++i){ for(int t:edges.get(i)){ res=Math.max(res,maxPath(i,t)[0]*maxPath(t,i)[0]); } } System.out.println(res); } static List<List<Integer>> edges; static int[] maxPath(int v, int prev){ Integer[] depths = {0,0,0}; int res = 0; for(int t:edges.get(v)){ if(t!=prev){ int[]r=maxPath(t,v); res=Math.max(res,r[0]); depths[0]=r[1]; Arrays.sort(depths); } } res = Math.max(res,depths[1]+depths[2]); return new int[]{res, depths[2]+1}; } }