手写邻接表 BFS
#include <iostream> #include <queue> using namespace std; const int maxn = 100000; const int maxm = 300000; struct Graph { int NE , NV; int head[maxn]; struct Node{ int next , v; Node(){} Node(int a,int b):v(a) , next(b){} }E[maxm]; void clear(int n) { NV = n; NE = 0; memset(head,-1,sizeof(int)*n); } inline void Insert(int u,int v) { E[NE] = Node(v , head[u]); head[u] = NE ++; } void Print() { for(int i = 0 ; i < NV ; i ++) { printf("%d:",i); for(int j = head[i]; j != -1; j = E[j].next){ printf(" %d",E[j].v); } puts(""); } } }G; int n, m, ctr; int visit[maxn]; void BFS(int cur) { queue<int> Q; Q.push(cur); visit[cur] = 1; while( !Q.empty() ){ for(int i = G.head[Q.front()]; i != -1; i = G.E[i].next ){ if(!visit[G.E[i].v]){ visit[G.E[i].v] = 1; Q.push(G.E[i].v); ctr++; if(ctr >= n - 1) printf("%d为根节点\n", cur); } } Q.pop(); } } int main(){ cin >> n;//读入顶点数 G.clear(n); cin >> m;//读入边数 int begin, end; for(int i = 0; i < m; ++i) { scanf("%d %d", &begin, &end); G.Insert(begin, end); } //遍历图 输出根节点 for(int i = 0; i < n; ++i){ memset(visit, 0, sizeof(visit)); ctr = 0; BFS(i); } return 0; }