您的位置:首页 > 其它

HDU 4634 Swipe Bo (BFS+状压)

2015-08-09 18:43 513 查看
哎,学到了~!@~!@

//#pragma comment(linker, "/STACK:102400000,102400000")
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<set>
#include<cmath>
#include<queue>
#include<cstring>
using namespace std;
const int M = 60005;
const int INF = 1e10;
//

struct node
{
int x, y;
int step;
int key;

} st, nx;

int dir[4][2] = { 1,0,-1,0,0,1,0,-1 };
int n, m;
char mp[205][205];
bool vis[205][205][1 << 7];
int ky[205][205];
int ans, cnt, cur, sx, sy;
bool bol[205][205][1 << 7][4];  //标记状态

int bfs()
{
queue<node>q;
memset(vis, 0, sizeof(vis));
st.x = sx;
st.y = sy;
st.step = 0;
st.key = 0;
cur = 0;
cnt = 0;
vis[st.x][st.y][st.key] = 1;
q.push(st);
memset(bol, 0, sizeof(bol));
while (!q.empty())
{
nx = q.front();
q.pop();
for (int i = 0; i < 4; ++i)
{
int xx = dir[i][0];
int yy = dir[i][1];
int s = nx.step;
int k = nx.key;
int x = nx.x;
int y = nx.y;
while (1)
{
if (mp[x][y] == 'L')
{
xx = 0;
yy = -1;
}
if (mp[x][y] == 'U')
{
xx = -1;
yy = 0;
}
if (mp[x][y] == 'D')
{
xx = 1;
yy = 0;
}
if (mp[x][y] == 'R')
{
xx = 0;
yy = 1;
}
//                if(mp[nx.x][nx.y]=='K')
//                {
//                    k|=ky[nx.x][nx.y];
//                }
//                cout<<"dg"<<endl;
if (xx == -1 && yy == 0)
{
cnt = 0;
}
else if (xx == 1 && yy == 0)
{
cnt = 1;
}
else if (xx == 0 && yy == 1)
{
cnt = 2;
}
else
{
cnt = 3;
}
if (bol[x][y][k][cnt])
{
break;
}
bol[x][y][k][cnt] = 1;
x += xx;
y += yy;
if (mp[x][y] == 'E' && k == (1 << ans) - 1)
{
//puts("asd");
cur = nx.step + 1;
return 1;
}
if (x < 0 || x >= n || y < 0 || y >= m || mp[x][y] == '#')
break;
if (mp[x][y] == 'L')
{
xx = 0;
yy = -1;
}
if (mp[x][y] == 'U')
{
xx = -1;
yy = 0;
}
if (mp[x][y] == 'D')
{
xx = 1;
yy = 0;
}
if (mp[x][y] == 'R')
{
xx = 0;
yy = 1;
}
if (mp[x][y] == 'K')
{
k |= ky[x][y];      //拾取钥匙
}
if (mp[x + xx][y + yy] == '#' && x + xx >= 0 && x + xx < n && y + yy >= 0 && y + yy < m)
{
if (vis[x][y][k])
break;
vis[x][y][k] = 1;
node nxx;
nxx.x = x;
nxx.y = y;
nxx.key = k;
nxx.step = nx.step + 1;
q.push(nxx);
break;
}

}

}

}
return 0;
}

int main()
{
while (~scanf("%d%d", &n, &m))
{
ans = 0;
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < m; ++j)
{
cin >> mp[i][j];
if (mp[i][j] == 'S')
{
sx = i;
sy = j;

}
if (mp[i][j] == 'K')
{
ky[i][j] = (1 << ans);  //储存钥匙
ans++;

}
}

}
if (bfs())
{
printf("%d\n", cur);
}
else
{
puts("-1");
}

}

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: