MDeath-Kid

- M I T & Y
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

POJ 1753

Posted on 2011-11-06 18:11  MDeath-Kid  阅读(230)  评论(0编辑  收藏  举报

可以看的出来,我现在的水平大大的下降了,不知道是不是发烧烧糊涂了。。就当是了。

这个题目DFS,BFS都能做,第一反应就是高斯消元,硬着头皮自己写了个BFS,发现什么都不会了,没hash判重,没有转移正确,都。。都恶心死自己了。

 

纠结了2个小时,终于A了。谢天谢地。

还有,POJ的hash_map不能用了,有谁知道怎么解决吗?BS下POJ

总结BFS

BFS
 1 // node
2 struct node {
3 int sta;
4 int step;
5 node(int a,int b) {
6 sta = a;
7 step = b;
8 }
9 };
10
11 //方向
12 int go[4][2] = {{1,0},{-1,0},{0,1},{0,-1}};
13
14 queue<node> Q;
15 //判重
16 map<int,bool> hamp;
17
18 //
19 int BFS() {
20 //初始化
21 SETQ(Q);hamp.clear();
22
23 //初始状态 - - 一个队列,一个判重
24 Q.push(node(sta,0));
25 hamp[sta] = 1;
26
27 node top(0,0);
28 //搜索
29 while(!Q.empty()) {
30 top = Q.front();Q.pop();
31 int sta = top.sta;
32 if(sta == 0 || sta == 65535) {
33 return top.step;
34 }
35 //转移
36 F(i,4) F(j,4) {
37 //每次转移的初始化
38 sta = top.sta;
39 sta ^= 1<<(xytoline(i,j));
40 F(k,4) {
41 int x=i,y=j;
42 x += go[k][0];
43 y += go[k][1];
44 if(x>=0 && x <4 && y>=0 && y<4) {
45 sta ^= 1<<(xytoline(x,y));
46 }
47 }
48 if(hamp.find(sta) == hamp.end())
49 Q.push(node(sta,top.step+1));
50 hamp[sta] = 1;
51 if(sta == 0 || sta == 0xffff) {
52 return top.step + 1;
53 }
54 }
55 }
56
57 return -1;
58 }

 

AC的代码

MDK 1753 Accepted 884K 282MS G++ 2550B 2011-11-06 17:59:21
POJ 1753
/***
BFS

*/

struct node {
int sta;
int step;
node(int a,int b) {
sta = a;
step = b;
}
};
int sta;
//方向
int go[4][2] = {{1,0},{-1,0},{0,1},{0,-1}};
char mat[5][5];

queue<node> Q;
//判重
map<int,bool> hamp;

int xytoline(int x,int y) {
return x * 4 + y;
}



int BFS() {
SETQ(Q);hamp.clear();

Q.push(node(sta,0));
node top(0,0);
hamp[sta] = 1;
while(!Q.empty()) {
top = Q.front();Q.pop();
int sta = top.sta;
if(sta == 0 || sta == 65535) {
return top.step;
}
//转移
F(i,4) F(j,4) {
sta = top.sta;
sta ^= 1<<(xytoline(i,j));
F(k,4) {
int x=i,y=j;
x += go[k][0];
y += go[k][1];
if(x>=0 && x <4 && y>=0 && y<4) {
sta ^= 1<<(xytoline(x,y));
}
}
if(hamp.find(sta) == hamp.end())
Q.push(node(sta,top.step+1));
hamp[sta] = 1;
if(sta == 0 || sta == 0xffff) {
return top.step + 1;
}
}
}

return -1;
}

int main () {

while(~SCFS(mat[0])) {
sta = 0;
SCFS(mat[1]);SCFS(mat[2]);SCFS(mat[3]);
//PP(5,5,mat);
char ctmp;
F(i,4) F(j,4) {
ctmp = mat[i][j];
if(ctmp == 'b') {
sta |= 1<<(xytoline(i,j));
}
}

int ans = BFS();
if(ans == -1) {
puts("Impossible");
} else {
PCFLN(ans);
}
}
}



mark下,这个题目这么多的神做法。。