51nod 2600 小Biu的旅行


原题链接

51nod 2600
题目类型: 2 2 2级题 ♦ ♦ {\color{green}{♦♦}}{\color{lightgreen}{}}{\color{yellow}{}}{\color{orange}{}}{\color{red}{}}
AC记录:Accepted

题目大意

小Biu所在的城市有 n n n个景点,有一些景点之间有单向联通的道路,现在小Biu在 1 1 1号景点上,他想知道到达除了 1 1 1号景点之外的每个景点分别最少需要经过多少条道路?

输入格式

1 1 1行:两个正整数 n , m n,m n,m n n n表示景点的个数, m m m表示路径的条数。(1<=n<=1000,1<=m<=3000)
2 2 2 m + 1 m+1 m+1行:每行两个 u , v u,v u,v,表示 u u u v v v有一条单向联通的道路,数据保证没有重边和自环。(1<=u,v<=n)

输出格式

输出 n − 1 n-1 n1行,第 i i i行表示从 1 1 1号景点到达 i + 1 i+1 i+1号景点最少要经过几条道路,如果不能到达则输出 − 1 -1 1
S a m p l e \mathbf{Sample} Sample I n p u t \mathbf{Input} Input

6 6
1 2
1 3
2 4
3 2
3 5
5 6

S a m p l e \mathbf{Sample} Sample O u t p u t \mathbf{Output} Output

1
1
2
2
3

H i n t & E x p l a i n \mathbf{Hint\&Explain} Hint&Explain
样例所示的图如下图所示。
Data Expalain

数据范围

对于 100 % 100\% 100%的数据, 1 ≤ n ≤ 1000 , 1 ≤ m ≤ 3000 1≤n≤1000,1≤m≤3000 1n1000,1m3000

解题思路

此题可以用诸多算法来解决,如最短路算法,等。这里主要是介绍如何使用 b f s bfs bfs过这题。
其实用 b f s bfs bfs也非常简单,就是从每一个节点开始按路径扩展,这里不再多讲。

注意这里的图是单向图,只用建立一条边就可以了。


最后,祝大家早日
AC

上代码

#include<bits/stdc++.h>

using namespace std;

vector<int>     road[200010];
queue<int>      q;
bool            vis[200010];
int             bfs[200010];
int             base[200010];
int             n,pos;

inline bool pd(int x,int y)
{
    return base[x]<base[y];
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cin>>n;
    for(int i=1; i<n; i++)
    {
        int x,y;
        cin>>x>>y;
        road[x].push_back(y);
        road[y].push_back(x);
    }
    for(int i=1; i<=n; i++)
    {
        int x;
        cin>>x;
        base[x]=i;
    }
    for(int i=1; i<=n; i++)
        sort(&road[i][0],&road[i][road[i].size()],pd);
    q.push(1);
    vis[1]=true;
    while(q.size())
    {
        int now=q.front();
        q.pop();
        bfs[now]=++pos;
        for(int i=0; i<road[now].size(); i++)
        {
            if(!vis[road[now][i]])
            {
                vis[road[now][i]]=true;
                q.push(road[now][i]);
            }
        }
    }
    for(int i=1; i<=n; i++)
    {
        if(bfs[i]!=base[i])
        {
            cout<<"No"<<endl;
            return 0;
        }
    }
    cout<<"Yes"<<endl;
    return 0;
}

完美切题 ∼ \sim

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值