如果仅仅是题目当中要求的求解树的直径,一次BFS就行了
#include<iostream>
#include<queue>
using namespace std;
int N;//邻接表存储树,N为树的节点数,将树仍然存储为无向图
//假设树的根节点的序号为0
typedef struct Tnode
{
int index;
struct Tnode *next;
}Tnode;
int main()
{
scanf("%d",&N);
int i,j;
bool *visited=new bool[N];
Tnode *tree=new Tnode[N];
for(i=0;i<N;i++)
{
tree[i].index=i;
tree[i].next=NULL;
visited[i]=false;
}
while(1)
{
int a,b;
scanf("%d %d",&a,&b);
if(a==0&&b==0)
break;//边的输入以“0 0”结束
Tnode *temp=&tree[a];
while(temp->next!=NULL)
temp=temp->next;
Tnode *t=new Tnode;
t->index=b;
t->next=NULL;
temp->next=t;
temp=&tree[b];
while(temp->next!=NULL)
temp=temp->next;
t=new Tnode;
t->index=a;
t->next=NULL;
temp->next=t;
}
queue<int> q;
q.push(0);
visited[0]=true;
int length=0;
while(!q.empty())
{
queue<int> q2;
while(!q.empty())
{
int t=q.front();
q.pop();
Tnode *tempp=tree[t].next;
while(tempp!=NULL)
{
if(!visited[tempp->index])
{
q2.push(tempp->index);
visited[tempp->index]=true;
}
tempp=tempp->next;
}
}
q=q2;
length++;
}
printf("%d\n",length);
return 0;
}
测试数据
14
14 8
13 8
12 7
11 6
10 5
9 4
4 1
1 0
2 0
3 0
5 2
2 6
2 7
3 8
0 0