voidadd(int a, int b){ e[idx] = b; // 添加边 b ne[idx] = h[a]; h[a] = idx++; }
voiddfs(int u){ set<int> set_save; // 每次递归调用时使用一个新的 set st[u] = true; cout << u << " "; for (int i = h[u]; i != -1; i = ne[i]) { int j = e[i]; if (!st[j]) { set_save.insert(j); } } for (int j : set_save) { dfs(j); } }
voidbfs(int u){ priority_queue<int> que; que.push(u); st[u] = true; while (!que.empty()) { int t = que.top(); que.pop(); cout << t << " "; for (int i = h[t]; i != -1; i = ne[i]) { int j = e[i]; if (!st[j]) { st[j] = true; que.push(j); } } } }
intmain(){ int a, b; cin >> n >> m; memset(h, -1, sizeof(h)); for (int i = 0; i < m; i++) { cin >> a >> b; add(a, b); }
voidadd(int a, int b){ e[idx] = b; // 添加边 b ne[idx] = h[a]; //下一条边的索引 h[a] = idx++; //该节点第一条边的索引 }
voiddfs(int u){ st[u] = true; cout << u << " "; for (int i = h[u]; i != -1; i = ne[i]) { int j = e[i]; if (!st[j]) { dfs(j); } } }
voidbfs(int u){ queue<int> que; que.push(u); st[u] = true; while (!que.empty()) { int t = que.front(); que.pop(); cout << t << " "; for (int i = h[t]; i != -1; i = ne[i]) { int j = e[i]; if (!st[j]) { st[j] = true; que.push(j); } } } }
intmain(){ ios::sync_with_stdio(false); cin.tie(nullptr); cin >> n >> m; memset(h, -1, sizeof(h)); for (int i = 0; i < m; i++) { int a, b; cin >> a >> b; node[i].x = a; node[i].y = b; } sort(node, node + m, [](nod a, nod b) { if (a.x != b.x) { return a.x < b.x; } else { return a.y > b.y; //由于h[a]的idx会被最后一条idx覆盖,因此我们应该倒序存储 } });
for (int i = 0; i < m; i++) { add(node[i].x, node[i].y); }