【广搜】Cyh和香穗子

Problem 3 Cyh和香穗子

  话说,Cyh和香穗子是好朋友,一天他们在fzsz迷路了….Cyh在地点1,香穗子在地点n.由于Cyh是土生土长的fzsz人,所以Cyh准备去n地给香穗子带路.

fzsz是个奇怪的地方,它由n地点组成,并且任意两个地点A,B满足要么A能到B,要么B能到A,要么都不能互相到达,一定不存在A和B都能互相到达.

  现在Cyh希望快点到达n地

 

输入:

       第一行两个数n,m

       接下来m行,每行两个数a,b,表示地点a能达到地点b

 

输出:

       Cyh最少经过的地点数

 

Sample Input

       4 5

       1 2

       2 3

       2 4

       1 3

       3 4

 

Sample Output

       3

 

数据范围:

       n<=100000,m<=500000,保正有解

 

 

可以用spfa求最短路

这里写宽搜的代码,很标准的题目

C++ Code

/*
C++ Code
http://oijzh.cnblogs.com
*/
#include<cstdio>
#include<cstdlib>
#include<queue>
using namespace std;
#define MAXN 100010

int n,m;
struct link{int y;link* next;};
link *head[MAXN];
bool h[MAXN];
struct record{int pos,step;};
queue<record>q;

void insert(int x,int y)
{
    link *node=new link;
    node->y=y;
    node->next=head[x];
    head[x]=node;
}

int main()
{
    freopen("3.in","r",stdin);
    freopen("3.out","w",stdout);
    scanf("%d%d",&n,&m);
    int i,x,y;
    for(i=1;i<=m;i++){scanf("%d%d",&x,&y);insert(x,y);}
    record temp,newtmp;
    link* node;
    temp.pos=1;temp.step=1;
    h[1]=true;q.push(temp);
    while(!q.empty())
    {
        temp=q.front();q.pop();
        node=head[temp.pos];
        while(node)
        {
            y=node->y;
            if(!h[y])
            {
                newtmp.pos=y;newtmp.step=temp.step+1;
                if(y==n){printf("%d",newtmp.step);exit(0);}
                h[y]=true;q.push(newtmp);
            }
            node=node->next;
        }
    }
    return 0;
}

 

 

转载于:https://www.cnblogs.com/oijzh/archive/2012/10/14/2723361.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值