fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int main() {
  5. // your code goes here
  6. int n, m;
  7. cin >> n >> m;
  8. vector<vector<int>> matrix(n+5);
  9.  
  10. for (int i = 1; i <= m; i++){
  11. int a, b;
  12. cin >> a >> b;
  13. matrix[a].push_back(b);
  14. matrix[b].push_back(a);
  15. }
  16.  
  17. int source = 1; // here we are taking source as 1 because our input will be as source 1.
  18. // this source will only work with our input.
  19. // for another input we have to change our source.
  20.  
  21. // vector<int> used(n+5,0);
  22. unordered_map<int, int> used;
  23. queue<int> q;
  24. q.push(source);
  25.  
  26. used[source] = 1;
  27. vector<int> leaves;
  28.  
  29. vector<int> b(n+5, 0);
  30. for (int i = 1; i <= n; i++){
  31. cin >> b[i];
  32. }
  33.  
  34. vector<int> answer(n+5, 0);
  35. answer[1] = b[1];
  36.  
  37. while(!q.empty()){
  38. int parent = q.front();
  39.  
  40. q.pop();
  41.  
  42. for (int i : matrix[parent]){
  43. if(used[i] == 0){
  44. q.push(i);
  45. used[i] = 1;
  46.  
  47. if(b[i] == 1){
  48. answer[i] = answer[parent] + 1;
  49. }
  50. else{
  51. answer[i] = answer[parent];
  52. }
  53. }
  54. }
  55.  
  56. }
  57.  
  58. for (int i = 1; i <= n; i++){
  59. cout << answer[i] << " ";
  60. }
  61.  
  62.  
  63. return 0;
  64. }
Success #stdin #stdout 0s 5332KB
stdin
5 4
1 2
2 3 
3 4 
4 5 
1 0 0 1 1
stdout
1 1 1 2 3