P5318 查阅文献

题意大概意思就是分别用dfs与bfs遍历一个图,特殊要求是从编号小的点开始遍历。
用邻接表存图,至今我也没想明白怎么才可以从编号小的点开始遍历,明白是排序,但是不知道如何排序,题解中的排序方法是:按照终点从大到小排序,终点相同则按照起点从小到大排序,就记住吧。

#include <iostream>
#include <algorithm>
#include <cstring>

using namespace std;

const int M = 1000010;
int h[M], e[M], ne[M], idx;
int n, m; 
bool st[M];
int q[M]; 

struct Node
{
    int x, y;
}node[M];

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

void dfs(int u)
{
    st[u] = true;
    cout << u << " ";
    
    for(int i = h[u]; i != -1; i = ne[i])
    {
        int j = e[i];
        if(!st[j]) 
        {
            dfs(j);
        }
    }
}

void bfs()
{
    int hh = 0, tt = 0;
    q[0] = 1;
    st[1] = true;
    cout << 1 << " ";
    
    while(hh <= tt)
    {
        int t = q[hh++];

        for(int i = h[t]; i != -1; i = ne[i])
        {
            int j = e[i];
            if(!st[j])
            {
                cout << j << " ";
                q[++tt] = j;
                st[j] = true;
            }
        }
    }
}

bool cmp(struct Node a, struct Node b)
{
    return (a.y > b.y) || (a.y == b.y && a.x > b.x);
}

int main()
{   
    memset(h, -1, sizeof h);

    cin >> n >> m;
    for(int i = 0; i < m; i++)
    {
        int a, b;
        cin >> a >> b;
        node[i] = {a, b};
    }

    sort(node, node+m, cmp);

    for(int i = 0; i < m; i++) add(node[i].x, node[i].y);
    cout << endl;
    for(int i = 0; i < m; i++) cout << node[i].x << " " << node[i].y << endl;
    cout << endl;
    dfs(1);
    cout << endl;
    memset(st, 0, sizeof st);
    bfs();

    return 0;
} 
原文地址:https://www.cnblogs.com/ZhengLijie/p/13424867.html