#2345 MLE 求调
查看原帖
#2345 MLE 求调
1202669
Gary0925楼主2024/8/20 14:57
#include <iostream>
#include <string>
#include <cmath>
#include <map>
#include <vector>
#include <set>
#include <queue>
#include <cstring>
#include <algorithm>
using namespace std;
vector <int> p[100005];
bool fh[100005] = { 0 };
int n, m, p1, p2, h = 1, k, no;
void dfs(int a)
{
    if (!fh[a]) cout << a << " ";
    fh[a] = 1;
    for (int i = 0; i < p[a].size(); i++) dfs(p[a][i]);
}
void bfs(int a)
{
    queue <int> s;
    int t, x, ts;
    s.push(a), fh[a] = 1;
    while (!s.empty())
    {
        ts = s.size();
        for (int i = 0; i < ts; i++)
        {
            x = s.front(), s.pop();
            cout << x << " ";
            for (int i = 0; i < p[x].size(); i++)
            {
                t = p[x][i];
                if (!fh[t]) s.push(t), fh[t] = 1;
            }
        }
    }
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0); cout.tie(0);
    cin >> n >> m;
    for (int i = 0; i < m; i++)
    {
        cin >> p1 >> p2;
        p[p1].push_back(p2);
    }
    for (int i = 1; i <= n; i++) sort(p[i].begin(), p[i].end());
    dfs(h);
    cout << "\n";
    memset(fh, 0, n + 1);
    bfs(h);
    return 0;
}
2024/8/20 14:57
加载中...