求助!数组模拟邻接表WA第一个TLE剩下4个
查看原帖
求助!数组模拟邻接表WA第一个TLE剩下4个
704081
ly_father楼主2022/9/2 22:58
#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

const int N = 1e5 + 10;

int n, m, k;
int h[N], e[N], ne[N], idx;
int q[N];
bool st[N];

void add(int a, int b)
{
    e[idx] = b, ne[idx] = h[a], h[a] = idx ++ ;
}

void dfs(int u)
{
    printf("%d ", u);
    if (st[u]) return ;
    st[u] = true;
    
    for (int i = h[u]; ~i; i = ne[i])
    {
        int j = e[i];
        if (!st[j])
            dfs(j);
    }
    
}

void bfs()
{
    memset(st, 0, sizeof st);
    
    int hh = 0, tt = 0;
    st[1] = true;
    q[0] = 1;
    
    while (hh <= tt)
    {
        int t = q[hh ++ ];
        st[t] = false;
        
        for (int i = h[t]; ~i; i = ne[i])
        {
            int j = e[i];
            if (!st[j])
            {
                st[j] = true;
                q[++ tt] = j;
            }
        }
    }
}

int main()
{
    cin >> n >> m;
    
    memset(h, -1, sizeof h);
    while (m -- )
    {
        int a, b;
        cin >> a >> b;
        add(a, b);
    }
    
    dfs(1);

    cout << endl;
    
    bfs();
    for (int i = 0; i < n; i ++ ) printf("%d ", q[i]);
    
    return 0; 
}
2022/9/2 22:58
加载中...