【hiho一下 第十一周】树中的最长路

【题目链接】:http://hihocoder.com/problemset/problem/1050

【题意】

【题解】

有一个经典的求树的直径的方法;
首先;
树的直径的两端的端点必然都在树的叶子上(或在根节点,考虑一条链的情况);

设f[i][0]表示离i这个点最远的叶子节点的距离
f[i][1]表示离i这个点第二远的叶子节点的距离
更新的话
f[x][0]=max(f[son][0]+1);
f[x][1] = max(second(f[son][0])+1);
则可以通过dp求出来所有的节点的f值,取max{f[i][0]+f[i][1]}就是它的直径了;
这里我们可以降成一维的即
ans = max(ans,f[x]+f[son]+1),f[x]=max(f[son]+1);
这里f[x]=max(f[son]+1)在ans更新完后才更新;
这个做法就等同于上面那个做法;

【Number Of WA

0

【完整代码】

#include <bits/stdc++.h>
using namespace std;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define LL long long
#define rep1(i,a,b) for (int i = a;i <= b;i++)
#define rep2(i,a,b) for (int i = a;i >= b;i--)
#define mp make_pair
#define pb push_back
#define fi first
#define se second
#define ms(x,y) memset(x,y,sizeof x)

typedef pair<int,int> pii;
typedef pair<LL,LL> pll;

const int dx[9] = {0,1,-1,0,0,-1,-1,1,1};
const int dy[9] = {0,0,0,-1,1,-1,1,-1,1};
const double pi = acos(-1.0);
const int N = 1e5+100;

int n,f[N],ans;
vector <int> G[N];

void dfs(int x,int fa)
{
    f[x] = 0;
    for (int y:G[x])
    {
        if (y==fa) continue;
        dfs(y,x);
        ans = max(ans,f[x]+f[y]+1);
        f[x] = max(f[x],f[y]+1);
    }
}

int main()
{
    //freopen("F:\\rush.txt","r",stdin);
    ios::sync_with_stdio(false),cin.tie(0);//scanf,puts,printf not use
    cin >> n;
    rep1(i,1,n-1)
    {
        int x,y;
        cin >> x >> y;
        G[x].pb(y),G[y].pb(x);
    }
    dfs(1,0);
    cout << ans << endl;
    return 0;
}
原文地址:https://www.cnblogs.com/AWCXV/p/7626350.html