题目链接
树是一种特殊的图,采用邻接表存储树结构
简单的深搜,AC代码
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1005;
struct edge{
int v, next;
}e[maxn];
int n, p[maxn], eid, tab[maxn];
void init(){
memset(p, -1, sizeof(p));
for(int i = 0; i <= n; i++)
tab[i] = 1;
eid = 0;
}
void insert(int u, int v){
e[eid].v = v;
e[eid].next = p[u];
p[u] = eid++;
}
int dfs(int s){
for(int j = p[s]; j != -1; j = e[j].next)
tab[s] += dfs(e[j].v);
return tab[s];
}
int main(){
cin>>n;
init();
int a, b;
for(int i = 0; i < n - 1; i++){
scanf("%d%d", &a, &b);
insert(a, b);
}
dfs(1);
for(int i = 1; i <= n; i++){
if(i != 1)
cout<<' ';
cout<<tab[i];
}
cout<<endl;
return 0;
}