洛谷P3174 [HAOI2009]毛毛虫
作者:互联网
树形DP,注意答案是节点数,我一直以为是边数懵逼了半个小时
#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; }
标签:include,洛谷,int,P3174,son,HAOI2009,ans,now,dp 来源: https://www.cnblogs.com/Hoyoak/p/11846964.html