Two Paths CodeForces - 14D(暴力+树的直径)

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
4
1 2
2 3
3 4
Output
1
Input
7
1 2
1 3
1 4
1 5
1 6
1 7
Output
0
Input
6
1 2
2 3
2 4
5 4
6 4
Output
4
我承认一开始被这个分数和她的标签吓着了。。
后来发现n最大才二百的时候,直接枚举每条边,删掉这条边之后形成两棵树。求这两棵树的直径,更新答案。
代码如下:

#include<bits/stdc++.h>
#define ll long long
using namespace std;

const int maxx=100+100;
vector<int> p[maxx];
int dp[maxx][2];
int ans;
int n;

inline int dfs(int u,int f)
{
	int sum=0;
	int max1=0,max2=0;
	for(int i=0;i<p[u].size();i++)
	{
		if(p[u][i]!=f)
		{
			sum=max(sum,dfs(p[u][i],u));
			if(ans>max1)
			{
				max2=max1;
				max1=ans;
			}
			else max2=max(max2,ans);
		}
	}
	sum=max(sum,max1+max2);
	ans=max1+1;
	return sum;
}
int main()
{
	int x,y;
	scanf("%d",&n);
	for(int i=1;i<n;i++)
	{
		scanf("%d%d",&x,&y);
		p[x].push_back(y);
		p[y].push_back(x);
	}
	int ans=0;
	int _max=0;
	for(int i=1;i<=n;i++)
	{
		for(int j=0;j<p[i].size();j++)
		{
			ans=0;
			int _max1=dfs(i,p[i][j]);
			int _max2=dfs(p[i][j],i);
			_max=max(_max,_max1*_max2);
		}
	}
	cout<<_max<<endl;
}

努力加油a啊,(o)/~

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

starlet_kiss

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值