http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1405
题意:
思路:
先求出所有点到根节点的距离,需要维护每棵子树的大小,然后就可以再来一次dfs依次求出别的点的距离。好像需要手动扩栈。
1 #pragma comment(linker, "/STACK:10240000,10240000") 2 #include<cstdio> 3 #include<cstring> 4 #include<vector> 5 #include<algorithm> 6 using namespace std; 7 const int maxn = 100000+5; 8 const int inf = 0x3f3f3f3f; 9 10 int n; 11 int num[maxn]; 12 long long d[maxn]; 13 vector<int> G[maxn]; 14 15 void dfs(int u, int fa, int dep) 16 { 17 num[u] = 1; 18 d[1] += dep; 19 for(int i=0;i<G[u].size();i++) 20 { 21 int v = G[u][i]; 22 if(v==fa) continue; 23 dfs(v,u,dep+1); 24 num[u] += num[v]; 25 } 26 } 27 28 void dfs2(int u, int fa) 29 { 30 for(int i=0;i<G[u].size();i++) 31 { 32 int v = G[u][i]; 33 if(v==fa) continue; 34 d[v] = d[u]+n-num[v]-num[v]; 35 dfs2(v,u); 36 } 37 } 38 39 int main() 40 { 41 //freopen("in.txt","r",stdin); 42 scanf("%d",&n); 43 for(int i=1;i<n;i++) 44 { 45 int u,v; 46 scanf("%d%d",&u,&v); 47 G[u].push_back(v); 48 G[v].push_back(u); 49 } 50 d[1] = 0; 51 dfs(1,0,0); 52 dfs2(1,0); 53 for(int i=1;i<=n;i++) printf("%lld\n",d[i]); 54 return 0; 55 }