这一题考察的其实就是求树的高度,知识点:
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;
}
基础:
#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;
}