P5318 【深基18.例3】查找文献 题解

题目传送门

#include <bits/stdc++.h>

using namespace std;

const int N = 100010;
int n, m, x, y;

vector<int> p[N];//邻接表
bool st[N];       //是否走过

//深度优先搜索
void dfs(int x) {
    //输出当前结点
    cout << x << " ";
    //找到x结点的所有边,依次检查是否走过,没走过需要走一下
    for (int i = 0; i < p[x].size(); i++)
        if (!st[p[x][i]]) st[p[x][i]] = true, dfs(p[x][i]);
}

//广度优先搜索
void bfs() {
    queue<int> q;
    q.push(1);
    while (!q.empty()) {
        int x = q.front();
        q.pop();
        cout << x << " ";
        //找到p的所有连接的结点
        for (int i = 0; i < p[x].size(); i++)
            if (!st[p[x][i]]) {
                st[p[x][i]] = true;
                q.push(p[x][i]);
            }
    }
}

int main() {
    //读取
    cin >> n >> m;
    //构建图
    for (int i = 1; i <= m; i++) {
        cin >> x >> y;
        p[x].push_back(y); //有向图,只需要单向加入;无向图需要成对加入
    }
    //每个结点的对点从小到大排下序
    //如果有很多篇文章可以参阅,请先看编号较小的那篇(因此你需要先排序)。
    for (int i = 1; i <= n; i++) sort(p[i].begin(), p[i].end());//每一个节点的所有相关边,由小到大排序

    //准备从第1个结点开始深度优先搜索,标识已使用
    st[1] = true;
    dfs(1);
    cout << endl;

    //多轮次的输出,一定要记得清空状态数组
    memset(st, false, sizeof st);

    //广度优先搜索
    st[1] = true;
    bfs();

    return 0;
}
原文地址:https://www.cnblogs.com/littlehb/p/15119175.html