NOIP2014寻找道路

哭唧唧本想着这么简单的题连调试都没有就交了然后90QAQQQQQQQQQ,良久,突然发现第二次bfs的判重数组居然开在了bfs里面而且没有清0,嘤嘤嘤,加一个清零然后就AC了QAQQQQQQQQQQQ

双bfs不解释没什么好说的

#include<cstdio>
#include<algorithm>
#include<iostream>
#define N 10005
#define M 200005
#define LL long long
using namespace std;
struct wakaka
{
       int x,y,next;
}e[M*2];
int u[M],v[M],dis[N],vis[N],ls[N],cnt,q[M*2];
int n,m,S,T;
LL read()
{
	LL x=0,f=1;char ch=getchar();
	while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
	while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
	return x*f;
}

void add(int x,int y)
{
     int t=++cnt;e[t].x=x;e[t].y=y;e[t].next=ls[x];ls[x]=cnt;
     }
     
void bfs()
{
     memset(vis,0,sizeof(vis));
     int h=0,t=1;q[t]=T;vis[T]=1;
     while (h<t)
     {
           h++;int x=q[h];
           for (int i=ls[x];i!=0;i=e[i].next)
           {
               if (!vis[e[i].y])
               {
                                q[++t]=e[i].y;
                                vis[e[i].y]=1;
                                }
               }
           }
     }
     
bool check(int x)
{
     for (int i=ls[x];i!=0;i=e[i].next)
     {
         if (!vis[e[i].y]) return 0;
         }
     return 1;
     }
            
bool work()
{
     int h=0,t=1;int vv[N];q[t]=S;memset(vv,0,sizeof(vv));vv[S]=1;
     while (h<t)
     {
           h++;int x=q[h];
//           cout<<x<<endl;
           if (!check(x)) continue;
           for (int i=ls[x];i!=0;i=e[i].next)
           {
               if (e[i].y==T) 
               {
                              int ans=dis[h]+1;
                              printf("%d\n",ans);
                              return 0;
                              }
               if (!vv[e[i].y])
               {
                               q[++t]=e[i].y;
                               vv[e[i].y]=1;
                               dis[t]=dis[h]+1;
                               }
               }  
           }
     return 1;
     }

int main()
{
    freopen("road.in","r",stdin);
    freopen("road.out","w",stdout);
    n=read(),m=read();
    for (int i=1;i<=m;i++)
    {
        u[i]=read(),v[i]=read();
        if (u[i]!=v[i]) add(v[i],u[i]);
        }
    S=read();T=read();
    bfs();
//    for (int i=1;i<=n;i++) cout<<vis[i]<<' ';
//    cout<<endl;
    if (!vis[S]) 
    {
                   puts("-1");
                   return 0;
                   }
    memset(ls,0,sizeof(ls));
    cnt=0;
    //cout<<-1;
    for (int i=1;i<=m;i++)
    {
        if (u[i]!=v[i]) add(u[i],v[i]);
        }
    if (work()) puts("-1");
    return 0;
}


你可能感兴趣的:(noip)