[Luogu3174] [HAOI2009] Caterpillar [dynamic programming tree dp]

3174 [HAOI2009] caterpillar 

Seek a node on the chain and brother nodes connected to the upper strand and the maximum

Each node in the chain have been overcharged once so early is set to 1, although not yet figure out why run the same as the diameter of the tree twice ...

 

#include<bits/stdc++.h>
using namespace std;
#define Max(x,y) (x)<(y)?(y):(x)
#define Min(x,y) (x)<(y)?(x):(y)
#define ll long long
#define rg register
const int N=300000+5,M=1000000+5,inf=0x3f3f3f3f,P=9999973;
int n,m,out[N],mxl=0,sf,ans=0;
template <class t>void rd(t &x){
    x=0;int w=0;char ch=0;
    while(!isdigit(ch)) w|=ch=='-',ch=getchar();
    while(isdigit(ch)) x=(x<<1)+(x<<3)+(ch^48),ch=getchar();
    x=w?-x:x;
}

int head[N],tot=0;
struct edge{int v,nxt;}e[N<<1];
void add(int u,int v){
    e[++tot]=(edge){v,head[u]},head[u]=tot;
}

void dfs(int u,int fa,int dis){
    if(dis>=mxl) mxl=dis,sf=u;
    ans=Max(ans,dis);
    for(int i=head[u];i;i=e[i].nxt)
    if(fa!=e[i].v) dfs(e[i].v,u,dis+out[u]);
}

int main(){
    freopen("in.txt","r",stdin);
    rd(n),rd(m);
    memset(out,-1,sizeof(out));
    for(int i=1,u,v;i<=m;++i) rd(u),rd(v),add(u,v),add(v,u),++out[u],++out[v];
    dfs(1,0,0);mxl=-1,ans=0;
    dfs(sf,0,0);
    printf("%d",ans+2);
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/lxyyyy/p/11210299.html