Codeforces Beta Round #14 (Div. 2) D. Two Paths 树形dp

时间:2024-07-11 11:03:02

D. Two Paths

题目连接:

http://codeforces.com/contest/14/problem/D

Description

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.

Sample Input

4

1 2

2 3

3 4

Sample Output

1

Hint

题意

给你一棵树,让你选择两条不相交的路径,使得长度的乘积最大。

题解:

枚举删除哪条边,然后再跑树形dp就好了。

感觉可以O(n),但是这个复杂度我就懒得去想了

代码

#include<bits/stdc++.h>
using namespace std;
const int maxn = 206;
vector<int> E[maxn];
int n,s;
int dfs(int x,int pre)
{
int r1=0,r2=0,t=0;
for(int i=0;i<E[x].size();i++)
{
int v=E[x][i];
if(v==pre)continue;
t=max(dfs(v,x),t);
if(s>r1)r2=r1,r1=s;
else r2=max(s,r2);
}
t=max(t,r1+r2);
s=r1+1;
return t;
}
int main()
{
scanf("%d",&n);
for(int i=1;i<n;i++)
{
int x,y;
scanf("%d%d",&x,&y);
E[x].push_back(y);
E[y].push_back(x);
}
int ans = 0;
for(int i=1;i<=n;i++)
{
for(int j=0;j<E[i].size();j++)
{
int a = dfs(E[i][j],i);
int b = dfs(i,E[i][j]);
ans=max(a*b,ans);
}
}
cout<<ans<<endl;
}