zoukankan      html  css  js  c++  java
  • 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;
    }
    
  • 相关阅读:
    TestNG 单元测试框架的使用
    HDU1255 覆盖的面积(线段树+扫描线)
    AcWing1169 糖果(差分约数)
    牛客 Treepath(树形dp)
    牛客 Shortest Path (dfs+思维)
    牛客 树(dfs序)
    牛客 城市网络(倍增)
    牛客 Borrow Classroom (LCA)
    CF710E Generate a String(dp)
    c#委托
  • 原文地址:https://www.cnblogs.com/littlehb/p/15119175.html
Copyright © 2011-2022 走看看