• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
magicat
博客园    首页    新随笔    联系   管理    订阅  订阅
P5318 【深基18.例3】查找文献

原题地址:P5318 【深基18.例3】查找文献

根据描述和样例 分析如下:

  1. 先对 边 u->v 排一个序,满足字典序的需求
  2. dfs和bfs 都要记录当前点是否已经被访问过了,若之前没被访问过,继续dfs或bfs。防止出现重复访问

代码如下:

#include<iostream>
#include<cstring>
#include<vector>
#include<set>
#include<map>
#include<queue>
#include<algorithm>
using namespace std;


int n,m;
int d1[100010],d2[100010];
bool st[100010];
vector<int> son[100010];
void dfs(int u)
{
    cout<<u<<" ";
    st[u]=true;
    for(auto v:son[u])
        if(st[v]==false)
            dfs(v);

}
void bfs()
{
    st[1]=true;
    queue<int> q;   q.push(1);
    while(!q.empty())
    {
        int u=q.front();q.pop();
        cout<<u<<" ";
        for(auto v:son[u])   
            if(st[v]==false)
            {
                st[v]=true;
                q.push(v);
            }
    }
}
int main()
{
    cin>>n>>m;
    for(int i=1;i<=m;i++)
    {
        int x,y;    cin>>x>>y;
        son[x].push_back(y);
    }
    for(int i=1;i<=n;i++)
        sort(son[i].begin(),son[i].end());
    dfs(1);    cout<<endl;
    memset(st,false,sizeof st);
    bfs();     cout<<endl;
    return 0;
}

 

 

 

 

本文来自博客园,作者:magicat,转载请注明原文链接:https://www.cnblogs.com/magicat/p/16535143.html

posted on 2022-07-30 15:47  magicat  阅读(332)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3