Diameter of more than 2019 cattle off school fourth A meeting-- tree

Meaning of the questions:

$ $ A n-tree nodes labeled $ k $ points so obtained to find that the maximum distance of a minimum $ k $ key nodes.

analysis:

Seeking problem is equivalent to the diameter of the tree, the minimum distance is the diameter of the other two rounded up.

There are two methods seek, first, dynamic programming, for each node, all child nodes $ d (i) $ (represented by the subtree rooted at $ I $ is the distance from the root to the leaves of the maximum) are seeking out, provided two front node D $ U $ $ $ value and $ v $, then $ d (u) + d (v) + 2 $ is the diameter of the tree.

Another twice the DFS, starting from any node key, to find the key from its furthest node $ Y $, $ Y $ departing from dfs find new farthest node $ $ Z, the diameter is formed.

Code:

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

const int maxn = 1e5 + 10;

struct Edge
{
    int to, w, next;
}edges[maxn*2];
int head[maxn], cnt;
int n, k;
int vis[maxn], dis[maxn];      //顶点编号
set<int>st;

void init()
{
    memset(head, -1, sizeof(head));
    cnt = 0;
}

inline void AddEdge(int a, int b, int id)
{
    edges[id].to = b;
    edges[id].w = 1;
    edges[id].next = head[a];
    head[a] = id;
}

int dis_v, max_dis;
void dfs(int v, int dis)
{
    //printf("%d %d\n", v, dis);
    vis[v] = 1;
    for(int i = head[v];i != -1;i = edges[i].next)
    {
        int u = edges[i].to;
        if(vis[u])  continue;
        if(st.find(u) != st.end())
        {
            if(dis+1 > max_dis)
            {
                max_dis = dis + 1;
                dis_v = u;
            }
        }
        dfs(u, dis+1);
    }
}

int main()
{
    init();
    scanf("%d%d", &n, &k);
    for(int i =  0;i < n-1;i++)
    {
        int a, b;
        scanf("%d%d", &a, &b);
        AddEdge(a, b, ++cnt);
        AddEdge(b, a, ++cnt);
    }
    for(int i = 0;i < k;i++)
    {
        int tmp;
        scanf("%d", &tmp);
        st.insert(tmp);
    }
    dfs(*(st.begin()), 0);  //printf("%d %d\n", dis_v, max_dis);
    memset(vis, 0, sizeof(vis));
    max_dis = 0;
    dfs(dis_v, 0); //printf("%d %d\n", dis_v, max_dis);
    printf("%d\n", (max_dis+1)/ 2);

    return 0;
}

 

Guess you like

Origin www.cnblogs.com/lfri/p/11259301.html