Problem: 树的深度计数

Problem: 树的深度计数

Time Limit: 1 Sec Memory Limit: 128 MB

Input

第一行是一个整数N(1≤N ≤50000),表示计算机的台数,计算机被编号为1…N。下面N-1行,每行包括两个整数X, Y,表示X和Y这两台计算机之间由一条网线连接。1号点为根

Output

给出N行,分别表示从1号到N号点,每个点的深度为多少1号点的深度为0

Sample Input

3
1 2
1 3

Sample Output

0
1
1

代码如下

#include<stdio.h>
int sum,n,s;
int pre[100001],now[100001],son[100001],dist[100001],pp[50001];
void tot(int a,int b) {
	pre[++sum]=now[a];
	now[a]=sum;
	son[sum]=b;
}
void dfs(int u,int r) {
	pp[u]=1;
	dist[u]=r+1;
	int ans=0,m=0;
	int i=now[u];
	while(i) {
		int k=son[i];
		if(!pp[k])
			dfs(k,r+1);
		i=pre[i];
	}
}
int main() {
	int a,b;
	scanf("%d",&n);
	int i=1;
	while(i<=n-1) {
		scanf("%d%d",&a,&b);
		tot(a,b);
		tot(b,a);
		i++;
	}
	dfs(1,-1);
	i=1;
	while(i<=n){
		printf("%d
",dist[i]);
		i++;
	}
	return 0;
}
原文地址:https://www.cnblogs.com/ZhaoChongyan/p/11740463.html