fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int bfs(int s, unordered_map<int, list<int>> adj){
  5. int count=0;
  6. list<int> queue; // Create a queue for BFS
  7. queue.push_back(s);
  8. list<int>::iterator i; // 'i' will be used to get all adjacent vertices of a vertex
  9.  
  10. while(!queue.empty()){
  11. count++;
  12. s = queue.front(); // Dequeue a vertex from queue and print it
  13. queue.pop_front();
  14. for (i = adj[s].begin(); i != adj[s].end(); ++i) // Get all adjacent vertices of the dequeued vertex s. If a adjacent has not been visited, then mark it visited and enqueue it
  15. queue.push_back(*i);
  16. }
  17. return count-1;
  18. }
  19.  
  20. int main(){
  21. int t; cin>>t;
  22. while(t--){
  23. int n,x; cin>>n>>x;
  24. unordered_map<int, list<int>> g;
  25. for(int i=0; i<n-1; i++){
  26. int a,b; cin>>a>>b;
  27. g[a].push_back(b);
  28. }
  29. for(auto i:g){
  30. vector<pair<int,int>> childs;
  31. cout<<i.first<<"--->";
  32. for(auto j:i.second){
  33. int temp= bfs(j,g);
  34. childs.push_back(make_pair(temp,j));
  35. }
  36. sort(childs.rbegin(), childs.rend());
  37. for(auto j:childs) cout<<j.first<<j.second<<'*';
  38. cout<<endl;
  39. }
  40. }
  41. return 0;
  42. }
Success #stdin #stdout 0s 5608KB
stdin
2
4 1
1 2
1 3
1 4
8 1
1 2
1 3
2 4
2 5
5 6
5 7
7 8
stdout
1--->04*03*02*
5--->17*06*
1--->52*03*
7--->08*
2--->35*04*