【HAOI2009】【毛毛虫】【树形dp】

来源:互联网 发布:生命倒计时软件 编辑:程序博客网 时间:2024/06/12 01:23

试题描述
对于一棵树,我们可以将某条链和与该链相连的边抽出来,看上去就象成一个毛毛虫,点数越多,毛毛虫就越大。例如下图左边的树(图 1 )抽出一部分就变成了右边的一个毛毛虫了(图 2 )。
这里写图片描述

输入数据
在文本文件 worm.in 中第一行两个整数 N , M ,分别表示树中结点个数和树的边数。
接下来 M 行,每行两个整数 a, b 表示点 a 和点 b 有边连接( a, b ≤ N )。你可以假定没有一对相同的 (a, b) 会出现一次以上。
输出数据
在文本文件 worm.out 中写入一个整数 , 表示最大的毛毛虫的大小。
样例输入
13 12
1 2
1 5
1 6
3 2
4 2
5 7
5 8
7 9
7 10
7 11
8 12
8 13
样例输出
11
测试数据范围
40% 的数据, N ≤ 50000
100% 的数据, N ≤ 300000
题解:
准确的来说深搜一遍就好了。注意父节点有时候也是要算上的。。

#include<iostream>#include<cstdio>#include<cstring>using namespace std;struct use{    int st,en;}b[1000001];int f[1000001],n,m,a,bb,cnt,ans,son[1000001],next[1000001],point[1000001];inline void add(int x,int y){    next[++cnt]=point[x];point[x]=cnt;    b[cnt].st=x;b[cnt].en=y;}inline void dp(int x,int fa){    int maxx(-100000),temp;    f[x]=son[x];    for (int i=point[x];i;i=next[i])      if (b[i].en!=fa)           {             dp(b[i].en,x);             ans=max(ans,maxx+f[b[i].en]+1+son[x]-2);             maxx=max(maxx,f[b[i].en]);             f[x]=maxx+son[x]-1;           }}int main(){    freopen("worma.in","r",stdin);    freopen("worma.out","w",stdout);    scanf("%d%d",&n,&m);    for (int i=1;i<=m;i++)      {          scanf("%d%d",&a,&bb);          add(a,bb);add(bb,a);          son[a]++;son[bb]++;      }    dp(1,0);    cout<<ans;}
0 0
原创粉丝点击