Description
图中有N个点,每两点间只有唯一的路径,对于这样一个给定的图,最大的“毛毛虫”会有多大。毛毛虫包含一条主链,毛毛虫中的节点,要不在主链上,要么和主链上某节点相邻,如下图所示有两只合法的毛毛虫,点数越多,毛毛虫越大。
Input
输入文件第一行两个整数N,M(N≤1000000)
接下来M行,每行两个整数a, b(a, b≤N)
你可以假定没有一对相同的(a, b)会出现一次以上。
Output
一个整数ans,表示最大的毛毛虫的大小。
Sample Input
5 4
1 2
1 3
4 1
5 1
Sample Output
5
Data Constraint
Hint
【数据规模】
1. 对于20%的数据,N≤200
2. 对于40%的数据,N≤5000
3. 对于100%的数据,N≤10^6
.
.
.
.
.
.
.
分析
我们可以先将每个点转化为一个带权的点,权为该点的度数, 然后就和在一棵树上求最长链一样了。
.
.
.
.
.
.
程序:
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int ans=0,q=0,head[1000010],tj[1000010],cnt=0;
struct edge
{
int to,from;
} e[2000010];
void add(int x,int y)
{
e[++cnt].to=y;e[cnt].from=head[x];head[x]=cnt;tj[x]++;
e[++cnt].to=x;e[cnt].from=head[y];head[y]=cnt;tj[y]++;
}
void dfs(int x,int y,int l)
{
if (l>ans)
{
ans=l;
q=x;
}
for (int i=head[x];i;i=e[i].from)
if (e[i].to!=y) dfs(e[i].to,x,l+tj[e[i].to]-1);
}
int main()
{
int n,m;
scanf("%d%d",&n,&m);
for (int i=1;i<=m;i++)
{
int a,b;
scanf("%d%d",&a,&b);
add(a,b);
}
dfs(1,0,tj[1]+1);
dfs(q,0,tj[q]+1);
printf("%d",ans);
return 0;
}