牛客小白月赛6 C 桃花 dfs 求树上最长直径

链接:https://www.nowcoder.com/acm/contest/136/C
来源:牛客网

题目描述

    桃花一簇开无主,可爱深红映浅红。

                                        ——《题百叶桃花》

    桃花长在桃树上,树的每个节点有一个桃花,调皮的HtBest想摘尽可能多的桃花。HtBest有一个魔法棒,摘到树上任意一条链上的所有桃花,由于HtBest法力有限,只能使用一次魔法棒,请求出Htbest最多可以摘到多少个桃花。

输入描述:

第一行有一个正整数n,表示桃树的节点个数。
接下来n-1行,第i行两个正整数a
i
,b
i
 ,表示桃树上的节点a
i
,b
i
之间有一条边。

输出描述:

第一行一个整数,表示HtBest使用一次魔法棒最多可以摘到多少桃花。
示例1

输入

复制
3
1 2
2 3

输出

复制
3
示例2

输入

复制
3
1 2
1 3

输出

复制
3
示例3

输入

复制
4
1 2
2 3
3 4

输出

复制
4

备注:

对于100%的测试数据:
1 ≤ n ≤ 1000000
数据量较大,注意使用更快的输入输出方式。

分析:
  求树上最长子链(最长直径)
  记录树上任意一结点到子树最远结点的最长距离和到父结点的最长距离
类似hdu2196
https://blog.csdn.net/qq_37493070/article/details/81285249
AC代码:
#include <map>
#include <set>
#include <stack>
#include <cmath>
#include <queue>
#include <cstdio>
#include <vector>
#include <string>
#include <bitset>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <algorithm>
#define ls (r<<1)
#define rs (r<<1|1)
#define debug(a) cout << #a << " " << a << endl
using namespace std;
typedef long long ll;
const ll maxn = 1e6+10;
const ll mod = 1e9+7;
const double pi = acos(-1.0);
const double eps = 1e-8;
vector<ll> e[maxn];
ll ans[maxn], cnt[maxn], n;
void dfs( ll x, ll fa ) {
    ans[x] = cnt[x] = 1;
    for( ll v : e[x] ) {
        if( v == fa ) {
            continue;
        }
        dfs( v, x );
        ans[x] = max( ans[x], max( ans[v], cnt[x]+cnt[v] ) );    //子树最长
        cnt[x] = max( cnt[x], cnt[v]+1 );  //结点到父结点最长
    }
}
int main() {
    ios::sync_with_stdio(0);
    cin >> n;
    for( ll i = 0, x, y; i < n-1; i ++ ) {
        cin >> x >> y;
        e[x].push_back(y), e[y].push_back(x);
    }
    dfs(1,0);
    cout << ans[1] << endl;
    return 0;
}

  

猜你喜欢

转载自www.cnblogs.com/l609929321/p/9499873.html