【C++】1021. Deepest Root (25)

本文介绍了一种使用广度优先搜索(BFS)算法来找出给定图中作为树时的最深根节点的方法,并提供了完整的代码实现。面对特定类型的输入数据,如包含多个连通组件的图,该算法能正确地识别并输出错误信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1021. Deepest Root (25)

时间限制
1500 ms
内存限制
32000 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

A graph which is connected and acyclic can be considered a tree. The height of the tree depends on the selected root. Now you are supposed to find the root that results in a highest tree. Such a root is calledthe deepest root.

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integer N (<=10000) which is the number of nodes, and hence the nodes are numbered from 1 to N. Then N-1 lines follow, each describes an edge by given the two adjacent nodes' numbers.

Output Specification:

For each test case, print each of the deepest roots in a line. If such a root is not unique, print them in increasing order of their numbers. In case that the given graph is not a tree, print "Error: K components" where K is the number of connected components in the graph.

Sample Input 1:
5
1 2
1 3
1 4
2 5
Sample Output 1:
3
4
5
Sample Input 2:
5
1 3
1 4
2 5
3 4
Sample Output 2:
Error: 2 components

1.这道题比较适合用bfs,而不是dfs

好吧,20分,有五分没有拿 

#include <iostream>
#include <string>
#include<vector>
#include<queue>
#include<string.h>
#include<algorithm>
using namespace std;
//bool mark[10001];
vector<vector <int>> a;
int level[10001]={0};
queue <int >q;

int bfs(int tt){
	level[tt]=1;
	q.push(tt);
	while(q.size()!=0){
		int tt=q.front();
		for(int i=0;i<a[tt].size();i++){
			if(level[a[tt][i]]==0){
				level[a[tt][i]]=level[tt]+1;
				q.push(a[tt][i]);
			}
		}
		q.pop();
	}

	return 0;
}

int maxl(int n){
	int max=-1;
	for(int i=0;i<n;i++){
		if(level[i]>max){
			max=level[i];
		}
	}
	return max;
}

int cmp(int a,int b){
	return a<b;
}

int main(){
	int N,i,j;
	freopen("in.txt","r",stdin);
	scanf("%d",&N);
	a.resize(N);
	for(i=0;i<N-1;i++){
		int a1,a2;
		scanf("%d%d",&a1,&a2);
		a1--;
		a2--;
		a[a1].push_back(a2);
		a[a2].push_back(a1);
	}
	int tt=0;
	bfs(tt);
	vector <int> maxit;
	int suo=maxl(N);
	int cc=0;
	for( i=0;i<N;i++){
		if(level[i]>0){
			cc++;
		}
		if(level[i]==suo){
			maxit.push_back(i);
		}
	}
	if(cc==N){
		memset(level,0,sizeof(level));
		tt=bfs(maxit[0]);
		suo=maxl(N);
		
		for( i=0;i<N;i++){

			if(level[i]==suo){
				maxit.push_back(i);
			}
		}

		sort(maxit.begin(),maxit.end(),cmp);
		for(i=0;i<maxit.size();i++){
			cout<<maxit[i]+1<<endl;
		}
	}else{
		int count=1;
		for(i=0;i<N;i++){
			if(level[i]==0){
				bfs(i);
				count++;
			}
		}
		printf("Error: %d components",count);

	}

	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值