fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int main() {
  5.  
  6.  
  7. int n ;
  8. cin>>n ;
  9. int b[n+1] = {0};
  10.  
  11. vector <int> G[n+1];
  12. int i = 1 ;
  13. while(i<=n-1){
  14. int x,y ;
  15. cin>>x>>y ;
  16. G[x].push_back(y);
  17. G[y].push_back(x);
  18. i++;
  19. }
  20.  
  21. i = 1 ;
  22. while(i<=n){
  23. cin>>b[i];
  24. i++;
  25. }
  26.  
  27. queue <int> q ;
  28. int used[n+1] = {0};
  29. used[1] = 1 ;
  30. q.push(1);
  31. int answer[n+1] = {0};
  32. answer[1] = b[1] ;
  33. while(!q.empty()){
  34.  
  35. int top = q.front();
  36. q.pop();
  37. int c = 0 ;
  38. for(auto u : G[top]){
  39. if(used[u]==0){
  40. c++;
  41. used[u] = 1 ;
  42. q.push(u);
  43.  
  44. answer[u] = b[u]+ answer[top];
  45.  
  46. }
  47.  
  48. else{
  49.  
  50. }
  51.  
  52. }
  53.  
  54. }
  55. i = 1 ;
  56. while(i<=n){
  57. cout<<answer[i];
  58. cout<<'\n';
  59. i++;
  60. }
  61.  
  62.  
  63.  
  64.  
  65. return 0 ;
  66. }
Success #stdin #stdout 0.01s 5320KB
stdin
5
1 2
2 3 
3 4 
4 5 
1 0 0 1 1
stdout
1
1
1
2
3