首页 > 其他 > 详细

洛谷 P2296 寻找道路 —— bfs

时间:2018-09-13 17:11:59      阅读:167      评论:0      收藏:0      [点我收藏+]

题目:https://www.luogu.org/problemnew/show/P2296

第一次用 Emacs 对拍,写了半天;

注意那个 is 赋值的地方很容易错,千万别反复赋值;

一道水题写了一个下午,崩溃。

代码如下:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
int const maxn=1e4+5,maxm=2e5+5;
int n,m,s,t,hd[maxn],ct,to[maxm],nxt[maxm],dis[maxn],hdf[maxn],tof[maxm],nxtf[maxm],ctf;
bool vis[maxn],is[maxn];
queue<int>q;
void add(int x,int y){to[++ct]=y; nxt[ct]=hd[x]; hd[x]=ct;}
void add2(int x,int y){tof[++ctf]=y; nxtf[ctf]=hdf[x]; hdf[x]=ctf;}
int rd()
{
  int ret=0,f=1; char ch=getchar();
  while(ch<0||ch>9){if(ch==-)f=-1; ch=getchar();}
  while(ch>=0&&ch<=9)ret=(ret<<3)+(ret<<1)+ch-0,ch=getchar();
  return ret*f;
}
void init()
{
  q.push(t); vis[t]=1; is[t]=1;
  while(q.size())
    {
      int x=q.front(); q.pop();
      for(int i=hdf[x],u;i;i=nxtf[i])
    {
      if(vis[u=tof[i]])continue;
      vis[u]=1; q.push(u); is[u]=1;//is=1
    }
    }
  for(int i=1;i<=n;i++)
    {
      //      if(vis[i]){is[i]=1; continue;}
      if(vis[i])continue;
      for(int j=hdf[i];j;j=nxtf[j])
    is[tof[j]]=0;
    }
}
void bfs()
{
  memset(vis,0,sizeof vis);
  while(q.size())q.pop();
  q.push(s); vis[s]=1;
  while(q.size())
    {
      int x=q.front(); q.pop();
      for(int i=hd[x],u;i;i=nxt[i])
    {
      if(vis[u=to[i]]||!is[u])continue;
      vis[u]=1; q.push(u); dis[u]=dis[x]+1;
    }
    }
}
int main()
{
  n=rd(); m=rd();
  for(int i=1,x,y;i<=m;i++)
    {
      x=rd(),y=rd();
      if(x==y)continue;
      add(x,y),add2(y,x);
    }
  s=rd(); t=rd();
  init(); 
  if(!is[s]){printf("-1\n"); return 0;}//
  bfs();
  if(!vis[t])printf("-1\n");
  else printf("%d\n",dis[t]);
  return 0;
}

 

洛谷 P2296 寻找道路 —— bfs

原文:https://www.cnblogs.com/Zinn/p/9641604.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!