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;
} 
posted @   Xxaj5  阅读(162)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端
点击右上角即可分享
微信分享提示