题目描述
在有向图G 中,每条边的长度均为1 ,现给定起点和终点,请你在图中找一条从起点到终点的路径,该路径满足以下条件:
1 .路径上的所有点的出边所指向的点都直接或间接与终点连通。
2 .在满足条件1 的情况下使路径最短。
注意:图G 中可能存在重边和自环,题目保证终点没有出边。
请你输出符合条件的路径的长度。
####输入输出格式
输入格式:
输入文件名为road .in。
第一行有两个用一个空格隔开的整数n 和m ,表示图有n 个点和m 条边。
接下来的m 行每行2 个整数x 、y ,之间用一个空格隔开,表示有一条边从点x 指向点y 。
最后一行有两个用一个空格隔开的整数s 、t ,表示起点为s ,终点为t 。
输出格式:
输出文件名为road .out 。
输出只有一行,包含一个整数,表示满足题目᧿述的最短路径的长度。如果这样的路径不存在,输出- 1 。
输入输出样例
输入样例#1:
3 2
1 2
2 1
1 3
输出样例#1:
-1
输入样例#2:
6 6
1 2
1 3
2 6
2 5
4 5
3 4
1 5
输出样例#2:
3
题目讲解
这道题是noip2014提高组的一道题,本题的做法是先把每条边正向存一遍,并且记录每条边的出度,然后再把边反向存一遍,从终点t开始做一遍dfs,把每个点的入读存下来,再和之前所存下的出度对比一下,如果相同则说明可以到达终点t,不想同则不能到达,并且标记一下,最后跑一遍最短路即可。
源代码
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<deque>
using namespace std;
struct arr{
int nd,nx,co,ff;
}bot1[500000],bot2[500000];
int head1[20000],head2[20000],ru[20000],chu[20000],f[20000],dis[20000],ff[20000];
int n,m,cnt1,cnt2,s,t;
deque<int>q;
inline void add1(int u,int v,int w){ bot1[++cnt1].nd=v; bot1[cnt1].co=w; bot1[cnt1].nx=head1[u]; head1[u]=cnt1; }
//邻接链表存边
inline void add2(int u,int v,int w){ bot2[++cnt2].nd=v; bot2[cnt2].co=w; bot2[cnt2].nx=head2[u]; head2[u]=cnt2; }
void dfs2(int u){//反向DFS,记录存反向边后的入读
for(int i=head2[u];i;i=bot2[i].nx)
if(!bot2[i].ff){
ru[bot2[i].nd]++;
bot2[i].ff=1;
dfs2(bot2[i].nd);
}
}
inline void SPFA(int s){
dis[s]=0;q.push_back(s);
while(!q.empty()){
int u=q.front();
q.pop_front();//双端队列
f[u]=0;
for(int i=head1[u];i;i=bot1[i].nx){
int v=bot1[i].nd;
if(dis[v]>bot1[i].co+dis[u]&&!f[bot1[i].nd]){
dis[v]=bot1[i].co+dis[u];
if(!ff[v]){
ff[v]=1;
if(q.empty()||dis[v]>dis[q.front()]) q.push_back(v);
[SLF优化](http://tzdyy.lofter.com/post/1e3cd119_10c05810)
else q.push_front(v);
}
}
}
}
}
inline int read() {//读入优化
int x=0,w=1;
char ch=0;
while(ch!='-'&&(ch<'0'||ch>'9')) ch=getchar();
if(ch=='-') w=-1,ch=getchar();
while(ch>='0'&&ch<='9')x=x*10+ch-48,ch=getchar();
return x*w;
}
int main(){
n=read();m=read();
memset(dis,0x3f,sizeof(dis));
for(int i=1;i<=m;i++){
int u=read(),v=read();
chu[u]++;//记录出度,作用见上面讲解
add1(u,v,1);//正向存一下边
add2(v,u,1);//反向存一下边
}
s=read();t=read();
dfs2(t);
for(int i=1;i<=n;i++)
if(ru[i]!=chu[i]) f[i]=1;//标记一下,在做spfa的时候如果的是1,就不将这个点加入到spfa中
SPFA(s);
if(dis[t]==0x3f3f3f3f)cout<<-1;
else printf("%d",dis[t]);
}