BZOJ1138: [POI2009]Baj 最短回文路

来源:互联网 发布:河北网络干部学院辅助 编辑:程序博客网 时间:2024/05/17 01:01

BFS

丑的不得了。。。

9.5s过的。。。。。

#include<cstdio>#include<iostream>#include<cstring>#include<queue>using namespace std;char c;inline void read(int &a){a=0;do c=getchar();while(c<'0'||c>'9');while(c<='9'&&c>='0')a=(a<<3)+(a<<1)+c-'0',c=getchar();}int F[401][401][30];int f[401][401];int Q,n,m;bool Map[401][401][30];bool Has[401][401][30];struct Chain{int y;int c;    Chain *next;    Chain(){next=0;}}*Head[10001],*Tail[10001],*Out[401][30];inline void insert(int a,int b,int c){Chain *Tp=new Chain;Tp->next=Head[a];Head[a]=Tp;Tp->c=c;Tp->y=b;swap(a,b);Tp=new Chain;Tp->next=Tail[a];Tail[a]=Tp;Tp->c=c;Tp->y=b;Tp=new Chain;Tp->next=Out[a][c];Out[a][c]=Tp;Tp->c=c;Tp->y=b;}struct Element{int x,y,c,d;};queue<Element> L,L2;int main(){    read(n),read(m);int i,j,k;    while(!L.empty())L.pop();Element Tp;while(m--){read(i),read(j);do  c=getchar();while(c<'a'||c>'z');insert(i,j,c-'a');Map[i][j][c-'a']=true;f[i][j]=1;Tp.x=i,Tp.y=j;Tp.c=c-'a';Tp.d=0;L2.push(Tp);Tp.x=i,Tp.y=j;Tp.c=-1;Has[i][j][c-'a']=true;L.push(Tp);}for(i=1;i<=n;i++)  f[i][i]=0;while(!L2.empty())  L.push(L2.front()),L2.pop();while(!L.empty()){    Tp=L.front();    if(Tp.x==1&&Tp.y==4)        Tp.x++,Tp.x--;if(Tp.c==-1)       {    for(Chain*tp=Head[Tp.y];tp;tp=tp->next) if(!Has[Tp.x][tp->y][tp->c]) Has[Tp.x][tp->y][tp->c]=true,L.push((Element){Tp.x,tp->y,tp->c,1});    }else   {       for(Chain*tp=Out[Tp.x][Tp.c];tp;tp=tp->next)          if(!f[tp->y][Tp.y]&&tp->y^Tp.y)             {             if(tp->y==5&&Tp.y==4) Tp.y++,Tp.y--;  f[tp->y][Tp.y]=Tp.d+2;                 for(Chain *tp2=Head[Tp.y];tp2;tp2=tp2->next)                   if(!Has[tp->y][tp2->y][tp2->c])                       Has[tp->y][tp2->y][tp2->c]=true,L.push((Element){tp->y,tp2->y,tp2->c,Tp.d+2});  }                  }L.pop();}read(Q);int last,New;read(last);while(--Q){    read(New);    if(New==last)      puts("0");elseprintf("%d\n",f[last][New]==0?-1:f[last][New]);    last=New;}return 0;}


0 0
原创粉丝点击