题目描述
对于一棵树,我们可以将某条链和与该链相连的边抽出来,看上去就象成一个毛毛虫,点数越多,毛毛虫就越大。例如下图左边的树(图 11)抽出一部分就变成了右边的一个毛毛虫了(图 22)。
输入格式
输入中第一行两个整数 N, MN,M,分别表示树中结点个数和树的边数。
接下来 MM 行,每行两个整数 a, ba,b 表示点 aa 和点 bb 有边连接(a, b \le Na,b≤N)。你可以假定没有一对相同的 (a, b)(a,b) 会出现一次以上。
#include<iostream>
#include<cstring>
using namespace std;
const int maxn=3e5+5;
int head[maxn];
struct node{
int to,next;
}edge[maxn<<1];
int cnt=0;
void add_edge(int from,int to)
{
edge[cnt].to=to;
edge[cnt].next=head[from];
head[from]=cnt++;
}
int s;
int du[maxn];
int as=0;
void dfs(int root,int pre,int all)
{
if(as<all) s=root,as=all;
for(int i=head[root];i!=-1;i=edge[i].next)
{
int to=edge[i].to;
if(to!=pre)
{
dfs(to,root,all+du[to]-2);
}
}
}
int main()
{
int n,m;cin>>n>>m;
memset(head,-1,sizeof(head));
for(int i=1;i<=n;i++) du[i]++;
for(int i=1;i<=m;i++)
{
int from,to;cin>>from>>to;
add_edge(from,to);
add_edge(to,from);
du[from]++;
du[to]++;
}
dfs(1,0,du[1]);
as=0;
dfs(s,0,du[s]);
cout<<as<<endl;
}