Luo Gu P3174 [HAOI2009] caterpillar

Tree-DP, note the answer is the number of nodes, I always thought it was senseless to force a few side for half an hour
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#define maxn 300010

using namespace std;

struct node
{
    int ed,len,nxt;
};
node edge[maxn<<1];
int n,m,first[maxn],cnt,dp[maxn][2],f[maxn],ans,d[maxn]; 
bool son[maxn];

inline void add_edge(int s,int e,int d)
{
    ++cnt;
    edge[cnt].ed=e;
    edge[cnt].len=d;
    edge[cnt].nxt=first[s];
    first[s]=cnt;
    return;
}

inline void dfs(int now,int fa)
{
    int son=0;
    for(register int i=first[now];i;i=edge[i].nxt)
    { 
        int e=edge[i].ed;
        if(e!=fa)
        {
            son++;
            dfs(e,now);
            if(dp[e][0]+edge[i].len>dp[now][0])
            {
                dp[now][1]=dp[now][0];
                dp[now][0]=dp[e][0]+edge[i].len;
            }
            else if(dp[e][0]+edge[i].len>dp[now][1]) dp[now][1]=dp[e][0]+edge[i].len;
            //else son++;
        }
    }
    //printf("%d:%d %d %d ",now,dp[now][0],dp[now][1],son);
    if(dp[now][0]==0) ans=max(ans,(int)(fa!=0));
    else if(dp[now][1]==0) ans=max(ans,dp[now][0]+son-1+(fa!=0)),dp[now][0]+=son-1;
    else  ans=max(ans,dp[now][0]+dp[now][1]+son-2+(fa!=0)),dp[now][0]+=son-1;
    //printf("%d\n",dp[now][0]);
    return;
}

int main()
{
    scanf("%d%d",&n,&m);
    for(register int i=1;i<=m;++i)
    {
        int s,e;
        scanf("%d%d",&s,&e);
        add_edge(s,e,1);
        add_edge(e,s,1);
    }
    dfs(1,0);
    printf("%d\n",ans+1); 
    return 0;
}

 

 
 
 

Guess you like

Origin www.cnblogs.com/Hoyoak/p/11846964.html