[Luogu P3174] [HAOI2009] caterpillar

Preface:

Although a lot of people and I think the same , But I wrote this shameless solution to a problem

topic:

link

main idea:

Taking a tree nodes a longest chain and it is connected to the junction of the total number of points

Ideas:

Take the chain:

With tree \ (DP \) can easily solve this problem:

\ (F_X \) represented by \ (X \) depth of the root of the tree

Transfer equation:

\[f_x=max\{f_y + 1 \} (y\in son(x))\]

So with \ (x \) for the root node of the tree is the longest chain \ (f_x \) plus the second largest sub-tree of depth, below the code area to \ (ans \) to represent.

Code:

void dp(int x, int root)
{
    f[x] = 1;
    int maxn = 0, lown = 0; //最大 与 次大
    for (int i = head[x]; i; i = next[i])
    {
        int y = to[i];
        if (y == root) continue;
        dp(y, x);
        if(f[y] > lown)
        {
            if(f[y] > maxn) lown = maxn, maxn = f[y];
            else lown = f[y];
        }
        f[x] = max(f[x], f[y] + 1);
    }
    ans = max(ans, f[x] + lown);
}

Node connected links:

That only add nodes around it, no longer recursion.

That we first \ (\ texttt {main () } \) record the number of each node's son

Then recursively can directly provoke the family to stay together!

Code:

void dp(int x, int root)
{
    f[x] = 1;
    int num = 0;
    int maxn = 0, lown = 0;
    for (int i = head[x]; i; i = next[i])
    {
        int y = to[i];
        if (y == root) continue;
        dp(y, x);
        if(f[y] > lown)
        {
            if(f[y] > maxn) lown = maxn, maxn = f[y];
            else lown = f[y];
        }
        f[x] = max(f[x], f[y] + son[x] - 1);  //减1是因为父结点也算进去了
    }
    ans = max(ans, lown + maxn + son[x] - 1);
}

int main()
{
    scanf("%d%d", &n, &m);
    for (int i = 1; i <= m; i++)
    {
        int x, y;
        scanf("%d%d", &x, &y);
        ADD(x, y);
        ADD(y, x);
        son[x] ++, son[y] ++;
    }
    dp(1, 0);
    printf("%d", ans);
    return 0;
}

I wish \ (CSP.rp ++ \)

Guess you like

Origin www.cnblogs.com/GJY-JURUO/p/12001305.html