1.注意对h数组进行初始化
2.边长数目M等于结点数量的两倍
3.根据题意,dfs初始距离应该为0
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
const int N = 10010,M = 20020;
int h[N],e[M],ne[M],idx;
int n,m;
int res;
bool st[N];
void add (int a,int b)
{
e[idx] = b;
ne[idx] = h[a];
h[a] = idx++;
}
void dfs(int u,int d)
{
res = max(d,res);
st[u] = true;
for(int i = h[u];i != -1;i = ne[i])
{
int j = e[i];
if(!st[j])
dfs(j,d+1);
}
}
int main()
{
int a,b;
cin >> n >> m;
memset(h,-1,sizeof h);
for(int i = 1;i <= n;i++)
{
cin >> a >> b;
add(a,b);
add(b,a);
st[i] = false;
}
dfs(m,0);
printf("%d",res);
return 0;
}