题目:https://pintia.cn/problem-sets/994805342720868352/problems/994805372601090048

常规BFS和DFS都可以,这里为了再熟悉一下BFS的写法,用了BFS
一开始从0开始求最值了,改成从1开始就过了

代码

  1. #include<vector>
  2. #include<algorithm>
  3. #include<iostream>
  4. #include<queue>
  5. using namespace std;
  6. const int maxn = 110;
  7. struct Node{
  8. int depth;
  9. vector<int> child;
  10. }node[maxn];
  11. int n, m;
  12. int depth_table[110] = {0};
  13. void BFS(){
  14. queue<int> q;
  15. q.push(1);
  16. node[1].depth = 1;
  17. while(!q.empty()){
  18. int top = q.front();
  19. q.pop();
  20. for(int i = 0; i < node[top].child.size(); i++){
  21. int child = node[top].child[i];
  22. node[child].depth = node[top].depth + 1;
  23. q.push(child);
  24. }
  25. }
  26. }
  27. void caculate(){
  28. int max_index = 1;
  29. for(int i = 1; i < maxn; i++) depth_table[node[i].depth]++;
  30. for(int i = 1; i < maxn; i++){
  31. if(depth_table[i] > depth_table[max_index]){
  32. max_index = i;
  33. }
  34. }
  35. printf("%d %d", depth_table[max_index], max_index);
  36. }
  37. int main(){
  38. scanf("%d%d", &n, &m);
  39. int id, child_num, child_temp;
  40. for(int i = 0; i < m; i++){
  41. scanf("%d%d", &id, &child_num);
  42. for(int j = 0; j < child_num; j++){
  43. scanf("%d", &child_temp);
  44. node[id].child.push_back(child_temp);
  45. }
  46. }
  47. BFS();
  48. caculate();
  49. return 0;
  50. }