其他分享
首页 > 其他分享> > 1021 Deepest Root

1021 Deepest Root

作者:互联网

使用邻接矩阵会有测试点超时,所以要用vector邻接表

#include<iostream>
#include<cstring>
#include<vector>
#include<algorithm>
using namespace std;
const int maxn=10010;
int n,m,maxdeep;
vector<int> G[maxn];
int depth[maxn];
int vis[maxn];
void DFS(int u,int deep){
	vis[u]=1;
	maxdeep=max(maxdeep,deep);
	for(int i=0;i<G[u].size();i++){
		if(!vis[G[u][i]]) DFS(G[u][i],deep+1);
	}
}
int main(){
	cin>>n;
	memset(depth,0,sizeof(depth));
	for(int i=1;i<n;i++){
		int d1,d2;
		scanf("%d%d",&d1,&d2);
		G[d1].push_back(d2);
		G[d2].push_back(d1);
	}
	for(int i=1;i<=n;i++){//n个依次作root 
		memset(vis,0,sizeof(vis));
		maxdeep=0; 
		DFS(i,1);
		for(int j=i+1;j<=n;j++){
			if(!vis[j]){
				int count=1;
				for(int k=j;k<=n;k++){
					if(!vis[k]){
						DFS(k,1);
						count++;
					}
				}printf("Error: %d components\n",count);
				return 0;
			}
		}
		depth[i]=maxdeep;
	}
	int max=0;
	for(int i=1;i<=n;i++){
		if(depth[i]>max) max=depth[i];
	}for(int i=1;i<=n;i++){
		if(depth[i]==max) printf("%d\n",i);
	}
    return 0;
}

标签:maxdeep,1021,int,deep,depth,maxn,Deepest,include,Root
来源: https://blog.csdn.net/qq_32719923/article/details/88553888