算法导论 第22章 22.2-8

如果仅仅是题目当中要求的求解树的直径,一次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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值