您的位置:首页 > 其它

HDU 5025

2015-06-29 03:07 393 查看
选拔赛(2)简单的状态压缩+bfs

屌洋直接用8维数组过的...代码美的一逼

题意:

  悟空(K)找唐僧(T),只能上下左右四个方向走,每步花费一个时间,碰到蛇精(S)需要额外花费一个时间去消灭,需要按照顺序(1, 2 ... k)搜集K把钥匙才能打开唐僧所在的房间。

 

总结:

  在读入矩阵的时候,把每个S换成其他的字符,比如(a, b, c...),这样再bfs的时候,碰到蛇精所在房间就可以直接判断当前蛇是否已经被杀死

  任何题目中bfs的时候不能修改原有的矩阵数据,(后来的节点还会走到这个点上)

  

if(a & b == 0){...}

if((a&b) == 0){...}


  下面的表达式才能正确判断,运算符优先级(可以在任何时候都把位运算放在括号里面)

  

#include <bits/stdc++.h>

const int MAXN = 100+5;

int n, k;
char ma[MAXN][MAXN];
// state compression
// the binary format of 31 is 11111
// there are at most 5 snakes in the maze
// so just use a binary digit bit to mark
// weather it has been visited or not
// e.g. when wukong kills sankes numbered 1, 2, 5
// the statement will be 10011(19)

bool vis[MAXN][MAXN][10][32];

// for direction Wukong can go
int dir[4][2] = { {0, 1}, {0, -1}, {1, 0}, {-1, 0}};

struct QueNode
{
int x, y, k, s, t;
QueNode(){}
// k is the number of keys wukong has
// s is the states of snakes (detail is the descriptioni of 'vis' above )
// t is the time
QueNode(int _x, int _y, int _k, int _s, int _t):x(_x), y(_y), k(_k), s(_s), t(_t){}

};

std::queue<QueNode> que;

int main()
{

// this code below will clutter the output
/* std::ios::sync_with_stdio(false); */

while(std::cin >> n >> k && (n||k)){

// init the variable
// the efficient way to clear a std::queue
// just create a empty_que and swap it with original queue
memset(ma, '#', sizeof ma);
memset(vis, false, sizeof vis);
std::queue<QueNode> empty_que;
std::swap(que, empty_que);

// the highlight point
// dealing with the snakes
// rename it to enable it to show which snake it is
int snake_num = 0;

for(int i = 1; i <= n; ++ i){
for(int j = 1; j <= n; ++ j){
std::cin >> ma[i][j];
if(ma[i][j] == 'S'){
ma[i][j] = (++snake_num) + 'a';
}
if(ma[i][j] == 'K'){
que.push(QueNode(i, j, 0, 0, 0));
vis[i][j][0][0] = true;
}
}
}

bool ok = false;

while(que.empty() == false){
QueNode u = que.front();
que.pop();
// while wukong reaches the room in which Monk tang is
// and wukong has enough keys
if(ma[u.x][u.y] == 'T' && u.k == k){
std::cout << u.t << std::endl;
ok = true;
break;
}
// if wukong enter the room with snake and has not killed the snake
// it takes 1 minute to kill it
if(ma[u.x][u.y] <= 'a'+5 && ma[u.x][u.y] >= 'a'+1){
int num = 1<<(ma[u.x][u.y] -'a'-1);

/* if( u.s & num == 0) */
// the statement above is wrong
// pay attention to operator precedence
if( (u.s&num) == 0){
u.s |= num;
++ u.t;
que.push(u);
vis[u.x][u.y][u.k][u.s] = true;
continue;
}
}

for(int i = 0; i < 4; ++ i){
QueNode v(u);
++ v.t;
v.x += dir[i][0];
v.y += dir[i][1];

if(ma[v.x][v.y] != '#'){
if(ma[v.x][v.y] - '0' == u.k + 1){
v.k = u.k + 1;
}
if(vis[v.x][v.y][v.k][v.s] == false){
vis[v.x][v.y][v.k][v.s] = true;
que.push(v);
}
}
}

}
if(ok == false){
puts("impossible");
}

}

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