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;
}