• 洛谷 P2296 寻找道路 —— bfs


    题目: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
    "); return 0;}//
      bfs();
      if(!vis[t])printf("-1
    ");
      else printf("%d
    ",dis[t]);
      return 0;
    }
  • 相关阅读:
    zabbix报警把特定的应用集发送给developer
    logstash 判断接口响应时间发送zabbix告警
    zabbix 对于logstash告警连续发邮件
    java使double保留两位小数的多方法
    Vagrant 和 docker
    golang binarySearch
    go channel实现
    5个jvm命令
    字符串匹配的Boyer-Moore算法
    Rabin-Karp 算法
  • 原文地址:https://www.cnblogs.com/Zinn/p/9641604.html
Copyright © 2020-2023  润新知