POJ 1324 BFS+二进制状态标记
STL容器开在函数体内和体外还能卡超时?涨姿势了
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
const int maxr = 30, maxc = 30;
int maze[maxr][maxc],vis[maxr][maxc][1<<15];
int dir[maxr];
int dx[4] = {1,0,-1,0};
int dy[4] = {0,-1,0,1};
int R,C,L,kase;
struct Node
{
int x,y,st,dis;
Node(int x,int y,int st,int dis):x(x),y(y),st(st),dis(dis){}
};
bool check(int x,int y,Node node)
{
if(x < 1 || y < 1 || x > R || y > C || maze[x][y]) return false;
for(int i = L-1; i >= 1; --i)
{
dir[i] = node.st&3;
node.st >>= 2;
}
int xx = node.x, yy = node.y;
for(int i = 1; i < L; ++i)
{
xx += dx[dir[i]], yy += dy[dir[i]];
if(xx == x && yy == y) return false;
}
return true;
}
queue<Node> q;
int BFS(Node nod)
{
kase++;
if(nod.x == 1 && nod.y == 1) return 0;
while(!q.empty()) q.pop();
q.push(nod); vis[nod.x][nod.y][nod.st] = kase;
while(!q.empty())
{
Node tmp = q.front(); q.pop();
for(int i = 0; i < 4; ++i)
{
int nx = tmp.x + dx[i], ny = tmp.y + dy[i];
if(nx == 1 && ny == 1) return tmp.dis+1;
if(!check(nx,ny,tmp)) continue;
int ndis = tmp.dis + 1, nst = (tmp.st >> 2) + (((i+2)%4) << (2*(L-2)));
if(vis[nx][ny][nst]==kase) continue;
vis[nx][ny][nst] = kase;
q.push(Node(nx,ny,nst,ndis));
}
}
return -1;
}
int main()
{
while(~scanf("%d%d%d",&R,&C,&L) && (R+C+L))
{
int x,y,nx,ny;
Node node(0,0,0,0);
scanf("%d%d",&node.x,&node.y);
x = node.x, y = node.y;
for(int i = 1; i < L; ++i)
{
scanf("%d%d",&nx,&ny);
for(int i = 0; i < 4; ++i)
{
if(x + dx[i] == nx && y + dy[i] == ny)
{
node.st = (node.st << 2) + i;
break;
}
}
x = nx, y = ny;
}
int blocks; scanf("%d",&blocks);
memset(maze,0,sizeof(maze));
for(int i = 0; i < blocks; ++i)
{
scanf("%d%d",&x,&y);
maze[x][y] = 1;
}
printf("Case %d: %d\n",kase,BFS(node));
}
}