标签:a10 eve index oid void ima size std using
法1:BFS
#include <bits/stdc++.h> #include <stdio.h> #include <stdlib.h> #include <queue> using namespace std; const int maxn = 100010; vector<int> temp[maxn]; int n,m; int num,maxnum,level = 1,maxLevel = 1; queue<int> que; void BFS(){ for(int i=0;i<temp[1].size();++i){ que.push(temp[1][i]); } level++; num = que.size(); maxnum = num; while(!que.empty()){ for(int i = 0;i<num;++i){ int digit = que.front(); for(int j=0;j<temp[digit].size();++j){ que.push(temp[digit][j]); } que.pop(); } num = que.size(); level++; if(que.size() > maxnum){ maxnum = que.size(); maxLevel = level; } } } int main(){ scanf("%d%d",&n,&m); for(int i=0;i<m;++i){ int father,number,son; scanf("%d%d",&father,&number); for(int j=0;j<number;++j){ scanf("%d",&son); temp[father].push_back(son); } } num = temp[1].size(); BFS(); printf("%d %d\n",maxnum,maxLevel); system("pause"); return 0; }
法2:DFS遍历
#include <bits/stdc++.h> #include <stdio.h> #include <stdlib.h> #include <queue> using namespace std; const int maxn = 110; vector<int>Node[maxn]; int hashTable[maxn] = {0};//记录每个层的节点数 void DFS(int index,int level){ hashTable[level]++; for(int j = 0;j<Node[index].size();++j){ DFS(Node[index][j],level+1); } } int main(){ int n,m,parent,k,child; scanf("%d%d",&n,&m); for(int i =0;i<m;++i){ scanf("%d%d",&parent,&k); for(int j =0;j<k;++j){ scanf("%d",&child); Node[parent].push_back(child); } } DFS(1,1); int maxLevel = -1,maxValue = 0; for(int i=1;i<maxn;++i){ if(hashTable[i]>maxValue){ maxValue = hashTable[i]; maxLevel = i; } } printf("%d %d\n",maxValue,maxLevel); system("pause"); return 0; }
树的遍历——A1094 The Largest Generation(25)(树的静态结构——> vector<int> Node[maxn]来表示)
标签:a10 eve index oid void ima size std using
原文地址:https://www.cnblogs.com/JasonPeng1/p/12234883.html