[HAOI2009] caterpillars - the diameter of the tree

In a tree, the set of all edges and directly connected to it a chain is referred to as a caterpillar, this point is referred to as the sub-graph size caterpillars. Seeking a tree in the largest caterpillars. \ (N \ leq 3 \ times10 ^ 5 \)

Solution

Each weight set point value \ (. 1-deg_i \) , and then to find the longest path, the answer is \ (ans + 2 \)

#include <bits/stdc++.h>
using namespace std;

const int N = 300005;

vector <int> g[N];
int n,m,vis[N],a[N],f[N],ans;

void dfs(int p) {
    vis[p]=1;
    f[p]+=a[p];
    for(int q:g[p]) {
        if(vis[q]) continue;
        f[q]=f[p];
        dfs(q);
    }
}

signed main() {
    ios::sync_with_stdio(false);
    cin>>n>>m;
    for(int i=1;i<=m;i++) {
        int u,v;
        cin>>u>>v;
        g[u].push_back(v);
        g[v].push_back(u);
        a[u]++;
        a[v]++;
    }
    for(int i=1;i<=n;i++) a[i]--;
    dfs(1);
    int mx=0;
    for(int i=1;i<=n;i++) if(f[mx]<f[i]) mx=i;
    memset(vis,0,sizeof vis);
    memset(f,0,sizeof f);
    dfs(mx);
    int my=0;
    for(int i=1;i<=n;i++) if(f[my]<f[i]) my=i;
    cout<<f[my]+2<<endl;
}

Guess you like

Origin www.cnblogs.com/mollnn/p/12395191.html