求助大佬
查看原帖
求助大佬
1384328
feng_0108楼主2024/12/8 15:19

求助,只能过样例,其他全部re

#include<bits/stdc++.h>
using namespace std;

const int N = 1e5 + 10;

struct node{
    int a, b;
}nd[N];

int n, m;
vector<int> h[N];
bool vis1[N], vis2[N];

bool cmp(node x, node y)
{
    if(x.a != y.a) return x.a < y.a;
    return x.b < y.b;
}

void dfs(int x)
{
    if(!vis1[x]) cout << x << ' ';
    vis1[x] = true;
    for(int i = 0; i < h[x].size(); i ++ )
        dfs(nd[h[x][i]].b);
}

void bfs()
{
    queue<int> q;
    q.push(1); cout << 1 << ' ';
    vis2[1] = true;
    while(q.size())
    {
        int t = q.front();
        q.pop();
        for(int i = 0; i < h[t].size(); i ++ )
        {
            if(!vis2[nd[h[t][i]].b]){
                vis2[nd[h[t][i]].b] = true;
                q.push(nd[h[t][i]].b);
                cout << nd[h[t][i]].b << ' ';
            }
        }
    }
}

int main()
{
    cin >> n >> m;
    for(int i = 0; i < m; i ++ )
        cin >> nd[i].a >> nd[i].b;
    sort(nd, nd + m, cmp);
    for(int i = 0; i < m; i ++ )
        h[nd[i].a].push_back(i);
    dfs(1);
    cout << endl;
    bfs();
    return 0;
}
2024/12/8 15:19
加载中...