Samkit5025

Untitled

Sep 24th, 2022
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.34 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. void dfs(map<int,vector<int>> &hm,vector<int> &door,int K, int src,int par,int count,int *totalLastroom,map<int,int> &room){
  5.     if(door[src]==1){
  6.         count++;
  7.     }
  8.  
  9.     if(count>K){
  10.         return;
  11.     }
  12.  
  13.     if(hm[src].size()==1 && src!=1 && count<=K){
  14.         (*totalLastroom)++;
  15.         room[src] = count;
  16.         return;
  17.     }
  18.  
  19.     for(auto i : hm[src]){
  20.         if(i!=par){
  21.             dfs(hm,door,K,i,src,count,totalLastroom,room);
  22.         }
  23.     }
  24. }
  25.  
  26. void roomsReached(int N, int K, vector<int> &door, vector<pair<int,int>> &edge){
  27.     map<int,vector<int>> hm;
  28.  
  29.     for(int i=0;i<N-1;i++){
  30.         hm[edge[i].first].push_back(edge[i].second);
  31.         hm[edge[i].second].push_back(edge[i].first);
  32.     }
  33.  
  34.     int totalLastRoom = 0;
  35.     map<int,int> lastRoomReached;
  36.  
  37.     dfs(hm,door,K,1,-1,0,&totalLastRoom,lastRoomReached);
  38.  
  39.     cout<<totalLastRoom<<endl;
  40.     for(auto i : lastRoomReached){
  41.         cout<<i.first<<" "<<i.second<<endl;
  42.     }
  43. }
  44.  
  45. int main(){
  46.     int N,K;
  47.     cin>>N>>K;
  48.    
  49.     vector<int> door(N+1);
  50.     for(int i=1;i<=N;i++){
  51.         cin>>door[i];
  52.     }
  53.  
  54.     vector<pair<int,int>> edge(N-1);
  55.     for(int i=0;i<N-1;i++){
  56.         int U,V;
  57.         cin>>U>>V;
  58.         edge[i] = make_pair(U,V);
  59.     }  
  60.  
  61.     roomsReached(N,K,door,edge);
  62. }
Advertisement
Add Comment
Please, Sign In to add comment