PAT(Advance)1021. Deepest Root

PAT(Advance)1021. Deepest Root

该题分制为25分。
题目链接https://pintia.cn/problem-sets/994805342720868352/problems/994805482919673856

题目给出图的边及两端结点序号,题目给的N<10000,他给出的测试用例很像邻接矩阵的存储方式,但是如果用邻接矩阵来存的话,会超出题目给的内存限制,所以要用邻接表来存储。需要进行两次深搜,第一个深搜是以各个点为起点的深搜,第二个深搜是为了查出测试样例是否有多个连通块,记录连通块数目后退出外层大循环。

#include<iostream>
#include<vector>
using namespace std;
const int maxn = 10100;
vector<int>Adj[maxn];
int n, tempDepth = 1, MAXD = 1;
bool vis[maxn] = { false };
int depth[maxn]={0};

void DFS(int index,int depth)
{
	vis[index] = true;
	if (depth > tempDepth)
	{
		tempDepth = depth;
	}
	for (int i = 0; i < Adj[index].size(); i++)
	{
		int temp = Adj[index][i];
		if (!vis[temp] && Adj[temp].size()!= 0)
		{
			vis[temp] = true;
			DFS(temp,depth+1);
		}
	}
}

int main()
{
	cin >> n;
	for (int i = 1; i < n; i++)
	{
		int u, v;
		cin >> u >> v;
		Adj[u].push_back(v);
		Adj[v].push_back(u);
	}
	int k = 1;
	for (int i = 1; i <= n; i++)
	{
		fill(vis, vis + maxn, false);
		tempDepth = 1;
		DFS(i, 1);
		depth[i] = tempDepth;
		for (int j = 1; j <= n; j++)
		{
			if (!vis[j])
			{
				k++;
				DFS(j,1);
			}
		}
		if (k > 1)
			break;
	}

	if (k > 1)
	{
		cout << "Error: " << k << " components";
	}
	else
	{
		for (int i = 1; i <= n; i++)
		{
			if (depth[i] > MAXD)
			{
				MAXD = depth[i];
			}
		}
		for (int i = 1; i <= n; i++)
		{
			if (depth[i] == MAXD)
			{
				cout << i << endl;
			}
		}
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值