➤ Problem Link : 369C. Valera and Elections
✅ C++ Solution :
#include<bits/stdc++.h> using namespace std; int cnt; vector<int> ans; bool dfs(int v,vector<pair<int,int> > adj[], int n,int req,int parent) { bool flag=0; for(int i=0;i<adj[v].size();i++) { if(adj[v][i].first==parent) continue; if(dfs(adj[v][i].first,adj,n,adj[v][i].second,v)) flag=1; } if(flag) return 1; else { if(req==2) { cnt++; ans.push_back(v); return 1; } return 0; } } int main() { int n,x,y,t; cin>>n; vector<pair<int,int> > adj[n+1]; for(int i=0;i<n-1;i++) { cin>>x>>y>>t; adj[x].push_back(make_pair(y,t)); adj[y].push_back(make_pair(x,t)); } ans.clear(); cnt=0; dfs(1,adj,n,1,-1); cout<<cnt<<"\n"; for(int i : ans) cout<<i<<" "; }
Thank you for your patience reading. If you enjoyed this post, I’d be very grateful if you’d help it spread by emailing it to a friend, or sharing it on Whatsapp or Facebook.
😇Happy Learning!!