P5908 猫猫和企鹅

猫猫和企鹅 - 洛谷

这一题考察的其实就是求树的高度,知识点:

1.树的存储 2.树的遍历(dfs) 3.树的高度

#include <iostream>
#include <cstring>
using namespace std;

const int N = 1e5 + 10, M = 2 * N;
int ne[M], e[M], idx, h[N];
int n, d;
bool st[N];
int dis[N];
int ans;

void add(int a, int b)//用邻接表存
{
    e[idx] = b, ne[idx] = h[a], h[a] = idx ++;
}

void dfs(int u, int cnt) //cnt记录到1的节点数
{ 
    st[u] = true;
    dis[u] = cnt; //dis存到1的距离
    for(int i = h[u]; i != -1; i = ne[i])
    {
        int j = e[i];
        if(!st[j])
        {
            st[j] = true;
            dfs(j, cnt + 1);
        }
    }
}

int main()
{
    cin >> n >> d;
    
    memset(h, -1, sizeof h);
    for(int i = 0; i < n - 1; i ++ )
    {
        int a, b;
        cin >> a >> b;
        
        add(a, b), add(b, a);
    }
    
    dfs(1, 0);
    
    for(int i = 1; i < n; i ++ ) 
    {
        if(dis[i] <= d) ans ++;
        // cout << dis[i] << ' ';
    }
    ans --;
    cout << ans << endl;
    return 0;
}

基础:

3699. 树的高度 - AcWing题库

#include <iostream>
#include <cstring>
using namespace std;

const int N = 1e5 + 10, M = 2 * N;
int ne[M], e[M], idx, h[N];
int n, d;
bool st[N];
int dis[N];
int ans;

void add(int a, int b)
{
    e[idx] = b, ne[idx] = h[a], h[a] = idx ++;
}

void dfs(int u, int cnt)
{ 
    st[u] = true;
    dis[u] = cnt;
    for(int i = h[u]; i != -1; i = ne[i])
    {
        int j = e[i];
        if(!st[j])
        {
            st[j] = true;
            dfs(j, cnt + 1);
        }
    }
}

int main()
{
    cin >> n >> d;
    
    memset(h, -1, sizeof h);
    for(int i = 0; i < n - 1; i ++ )
    {
        int a, b;
        cin >> a >> b;
        
        add(a, b), add(b, a);
    }
    
    dfs(d, 0);  //求出到指定根节点的距离
    
    for(int i = 1; i < n; i ++ ) 
    {
        ans = max(dis[i], ans); //求最大距离
        // cout << dis[i] << ' ';
    }
    cout << ans << endl;
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值