bzoj1687: [Usaco2005 Open]Navigating the City 城市交通
输出方案bfs。刷一刷usaco增加信心。
代码
#include<cstdio>
#include<cstring>
using namespace std;
struct pt
{int x,y;}s,tp,t2,e,lst[60][80],q[1000000];
int tms,i,j,n,m,d[60][80],h,t,lk[4800];
int xx[]={1,0,-1,0},yy[]={0,1,0,-1};
bool mp[60][80];
char ch,ans[]={'S','E','N','W'};
void cal(int X,int Y)
{
if(X==s.x&&Y==s.y)return;
cal(lst[X][Y].x,lst[X][Y].y);
for(i=0;i<4;i++)
if(lst[X][Y].x+xx[i]==X&&lst[X][Y].y+yy[i]==Y)
lk[t++]=i;
}
int main()
{
memset(d,0x3f,sizeof(d));
scanf("%d%d",&n,&m),n=(n<<1)-1,m=(m<<1)-1;
for(i=0;i<n;i++)
{
getchar();
for(j=0;j<m;j++)
{
ch=getchar();
mp[i][j]=!(ch=='.');
if(ch=='S')s.x=i,s.y=j;
if(ch=='E')e.x=i,e.y=j;
}
}
d[s.x][s.y]=0,q[0]=s;
while(h<=t)
{
tp=q[h++];
if(d[tp.x][tp.y]>=d[e.x][e.y])continue;
for(i=0;i<4;i++)
{
t2.x=tp.x+xx[i],t2.y=tp.y+yy[i];
if(t2.x>=0&&t2.x<n&&t2.y>=0&&t2.y<m&&
mp[t2.x][t2.y]&&d[t2.x][t2.y]>d[tp.x][tp.y]+1)
d[t2.x][t2.y]=d[tp.x][tp.y]+1,lst[t2.x][t2.y]=tp,q[++t]=t2;
}
}
t=0,h=4;
cal(e.x,e.y);
for(int i=0;i<t;i+=2)
{
if(lk[i]!=h)
{
if(tms)printf(" %d\n",tms);
tms=1;
putchar(ans[h=lk[i]]);
}
else tms++;
}
printf(" %d\n",tms);
}