洛谷P5318

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

心态不好,得多做点水题

点击查看代码
#include<bits/stdc++.h>
using namespace std;

const int N = 1e5 + 10;

priority_queue<int, vector<int>, greater<int>> mp[N];
vector<bool>ck(N, 0);
vector<bool>ck2(N, 0);
queue<int> q;

void bfs(int start) {
    q.push(start);
    while(!q.empty()) {
        int now = q.front();
        q.pop();
        while(!mp[now].empty()) {
            q.push(mp[now].top());
            mp[now].pop();
        }
        if(!ck2[now]) {
            cout << now << ' ';
            ck2[now] = 1;
        } else {
            continue;
        }
    }
}

void dfs(int p) {
    if(!ck[p]) {
        cout << p << ' ';
        ck[p] = 1;
    }
    else return;
    auto mpcp = mp[p];
    while(!mpcp.empty()) {
        dfs(mpcp.top());
        mpcp.pop();
    }
}

int main() {
    int n, m; cin >> n >> m;
    for(int i = 0; i < m; i++) {
        int x, y;
        cin >> x >> y;
        mp[x].push(y);
    }
    dfs(1);
    cout << '\n';
    bfs(1);
    cout << '\n';
    return 0;
}
posted @ 2025-05-18 16:13  Chuan81  阅读(5)  评论(0)    收藏  举报