2020 Winter Holiday [gmoj2173] [Unrooted Tree] [dfs + enumeration]

Title description

Weiwei is very interested in trees recently. What is a tree? A tree is an acyclic connected undirected graph formed by n points and n-1 edges.
In this year's 2012 Zhejiang Provincial Team Selection Competition, Weiwei discovered the longest chain in the tree (that is, the farthest point pair among the trees) test questions, so she set about doing some research and thinking on the tree.
Weiwei wanted to know in the research process, for an unrooted tree, what is the height of the tree when node i is the root. The so-called tree height refers to the total number of nodes passing from the root node to the leaf node farthest from the root node. For details, see the input and output sample 1.
Weiwei now encounters some annoying things, do not want to continue thinking, please help her solve this problem.

Input

The input file is named tree.in and has N lines. The first line is a positive integer N, indicating the number of nodes in the tree. In line 2 to line N, two positive integers a and b separated by spaces in each line indicate that a and b are connected.

Output

The output file tree.out has N lines, and the i-th line indicates the height of the tree when node i is the root.

Sample input

[Sample input 1]

3
1 2
2 3

[Sample input 2]

4
1 4
2 4
3 4

Sample output

[Sample output 1]

3
2
3

[Sample output 2]

3
3
3
2

Data range limitation

For 100% data, 1≤N≤1000, 1≤a, b≤N

hint

Insert picture description here

analysis

Adjacency matrix connects edges, then enumerates roots. Then dfs finds the deepest node.

Code on

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
int n,a[1001][1001],mx,d[10001]; 
void dfs(int x,int k)
{
	if(k>mx) mx=k;
	d[x]=1;
	for(int i=1;i<=a[x][0];i++)
	{
		if(d[a[x][i]]==0)
		{
			dfs(a[x][i],k+1);
		}
	}
}
int main()
{
	freopen("tree.in","r",stdin);
	freopen("tree.out","w",stdout); 
    cin>>n;
    for(int i=1;i<=n-1;i++)
    {
    	int x,y;
    	cin>>x>>y;
    	a[x][0]++;
    	a[x][a[x][0]]=y;
		a[y][0]++;
		a[y][a[y][0]]=x; 
	}
	for(int i=1;i<=n;i++)
	{
		mx=0;//每次初始化 
		memset(d,0,sizeof(d));
		dfs(i,1);
		cout<<mx<<endl; 
	}
	fclose(stdin);
	fclose(stdout);
    return 0;
}

Published 110 original articles · 100 praises · 8035 visits

Guess you like

Origin blog.csdn.net/dglyr/article/details/104806441