fork download
  1. #include <iostream>
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4.  
  5. int main(){
  6. int n;
  7. cin>>n;
  8.  
  9. int m=n-1;
  10. vector<vector<int>>graph(n);
  11. int i=1;
  12. while(i<=m){
  13. int x,y;
  14. cin>>x>>y;
  15. x--,y--;
  16.  
  17. graph[x].push_back(y);
  18. graph[y].push_back(x);
  19. i++;
  20. }
  21.  
  22.  
  23. vector<int>value(n);
  24. for(int i=0;i<n;i++){
  25. cin>>value[i];
  26. }
  27.  
  28.  
  29. int source=0;
  30. vector<bool>visited(n,false);
  31. visited[source]=true;
  32.  
  33. queue<int>q;
  34. q.push(source);
  35.  
  36. vector<int>ones(n);
  37.  
  38. ones[0]=value[0];
  39.  
  40. while(!q.empty()){
  41. int parent=q.front();
  42. q.pop();
  43.  
  44. for(auto it:graph[parent]){
  45. if(!visited[it]){
  46. visited[it]=true;
  47. q.push(it);
  48.  
  49. if(value[it]==1){
  50. ones[it]=ones[parent]+1;
  51. }
  52. else{
  53. ones[it]=ones[parent];
  54. }
  55. }
  56. }
  57. }
  58.  
  59.  
  60. for(int i=0;i<n;i++){
  61. cout<<"Node"<<i+1<<" : "<<ones[i]<<endl;
  62. }
  63. return 0;
  64. }
Success #stdin #stdout 0.01s 5312KB
stdin
5
1 2
2 3
3 4
4 5
1 0 0 1 1
stdout
Node1 : 1
Node2 : 1
Node3 : 1
Node4 : 2
Node5 : 3