D. Book of Evil

原题链接

题解

题目要求有多少个点,其到标记点的最远距离不超过 \(d\)

看到这个我们不难想到树的直径:设直径端点 \(a,b\),树上任意一点 \(c\) 到叶子节点的距离 \(\leq max(d(c,a),d(c,b))\)

所以,我们把标记点看成叶子节点,并找出相距最远的一对标记点 \(ab\),如果某点与 \(a,b\) 的距离都不超过 \(d\) 则与其他标记点的距离也不会超过 \(d\)

(如果有非标记点,在叶子节点的“外侧”,该性质依然成立)

code

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

vector<int> G[100004];
bool mark[100005]={0};

int maxh=0;
int node1;
int node2;

void dfs(int now,int fa,int height)
{

    if(height>maxh&&mark[now])
    {
        maxh=height;
        node1=now;
    }
    for(auto next:G[now])
    {
        if(next==fa) continue;
        dfs(next,now,height+1);
    }
}

int ans[100005]={0};
int n,m,d;

void dfs1(int now,int fa,int height)
{
    if(height<=d) ans[now]++;
    if(height>maxh&&mark[now])
    {
        maxh=height;
        node2=now;
    }
    for(auto next:G[now])
    {
        if(next==fa) continue;
        dfs1(next,now,height+1);
    }
}

void dfs2(int now,int fa,int height)
{
    if(height<=d) ans[now]++;

    for(auto next:G[now])
    {
        if(next==fa) continue;
        dfs2(next,now,height+1);
    }
}


void solve()
{
    cin>>n>>m>>d;

    int start;
    for(int i=1;i<=m;i++)
    {
        int x;
        cin>>x;
        mark[x]=1;
        start=x;
    }

    for(int i=1;i<n;i++)
    {
        int x,y;
        cin>>x>>y;
        G[x].push_back(y);
        G[y].push_back(x);
    }

    node1=start;
    dfs(start,start,0);

    maxh=0;
    node2=start;
    dfs1(node1,node1,0);

    dfs2(node2,node2,0);

    int sum=0;
    for(int i=1;i<=n;i++) sum+=(ans[i]==2);
    cout<<sum<<'\n';
}
int main()
{
    ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
    int t=1;
    //cin>>t;
    while(t--) solve();
    return 0;
}


posted @ 2024-07-15 14:30  纯粹的  阅读(9)  评论(0)    收藏  举报