codeforces 14D(搜索+求树的直径模板)

D. Two Paths
time limit per test
2 seconds
memory limit per test
64 megabytes
input
standard input
output
standard output

As you know, Bob's brother lives in Flatland. In Flatland there are n cities, connected by n - 1 two-way roads. The cities are numbered from 1 to n. You can get from one city to another moving along the roads.

The «Two Paths» company, where Bob's brother works, has won a tender to repair two paths in Flatland. A path is a sequence of different cities, connected sequentially by roads. The company is allowed to choose by itself the paths to repair. The only condition they have to meet is that the two paths shouldn't cross (i.e. shouldn't have common cities).

It is known that the profit, the «Two Paths» company will get, equals the product of the lengths of the two paths. Let's consider the length of each road equals 1, and the length of a path equals the amount of roads in it. Find the maximum possible profit for the company.

Input

The first line contains an integer n (2 ≤ n ≤ 200), where n is the amount of cities in the country. The following n - 1 lines contain the information about the roads. Each line contains a pair of numbers of the cities, connected by the road ai, bi (1 ≤ ai, bi ≤ n).

Output

Output the maximum possible profit.

Examples
Input
Copy
4
1 2
2 3
3 4
Output
1
Input
Copy
7
1 2
1 3
1 4
1 5
1 6
1 7
Output
0
Input
Copy
6
1 2
2 3
2 4
5 4
6 4
Output
4

一个很玄的结论:树的直径的长度一定会是某个点的最长距离Hmax与次长距离Hsec之和(似乎不是结论,是dp)
根据这个结论,可以较为简单(dfs对我来说并不简单)的求出树的直径。

附ac代码:
 1 #include<iostream>
 2 #include<cstring>
 3 using namespace std;
 4 const int mm=233;
 5 int map[mm][mm];
 6 int n,ans;
 7 int dep;
 8 int dfs(int u,int p)
 9 {
10   int max1=0,max2=0;
11   int path_max=0;
12   for(int i=1;i<=n;i++)
13     if(map[u][i]&&i!=p)
14   {
15     int z=dfs(i,u);
16     if(path_max<z)path_max=z;
17     if(max1<dep)///更新当前点的两条最长路径
18     {
19       max2=max1;max1=dep;
20     }
21     else if(max2<dep)max2=dep;
22 
23   }
24   if(path_max<max1+max2)path_max=max1+max2;///最长路径等于最长两条分路径和
25   dep=max1+1;///更新上层最大深度为当前层最大深度
26   return path_max;
27 }
28 
29 int main()
30 {
31   int a,b;
32   while(cin>>n)
33   { memset(map,0,sizeof(map));
34     for(int i=0;i<n-1;i++)
35     {
36       cin>>a>>b;map[a][b]=map[b][a]=1;
37     }
38     ans=0;
39     for(int i=1;i<=n;i++)
40       for(int j=1;j<=n;j++)
41       if(map[i][j])
42     {
43       int a=dfs(i,j);
44       int b=dfs(j,i);
45       if(ans<a*b)
46         ans=a*b;
47     }
48     cout<<ans<<"\n";
49   }
50 }
View Code

 

学习博客:http://blog.csdn.net/nealgavin/article/details/8505981

posted @ 2018-03-02 15:34  euzmin  阅读(199)  评论(0编辑  收藏  举报