A Za, A Za, Fighting...

坚信:勤能补拙

PKU 1753 Flip Game

问题:
http://acm.pku.edu.cn/JudgeOnline/problem?id=1753

思路:
首先,观察题意,可以发现对于每个piece,最多只有两种可能性: 翻转一次或者不翻转,翻转多次是没有意义的
另外,由于整个rectangular大小是4X4,因此可以使用位运算来提高性能

对于位运算,需要知道的是如何反转任意的某一位:
巧妙的异或运算 1^x = ~x  0^x = x

1. 深度优先搜索
 1 #define SIZE 4
 2 #define BIT_MAX 16
 3 const int END_BLACK = 0;
 4 const int END_WHITE = (1<<(BIT_MAX))-1;
 5 int min;
 6 
 7 int
 8 flip(int init_state, int bit_num)
 9 {
10     int x, y;
11     x = bit_num / SIZE;
12     y = bit_num % SIZE;
13     init_state ^= (1<<bit_num);
14     if(x == 0)
15         init_state ^= (1<<(bit_num+SIZE));
16     else if(x == 3)
17         init_state ^= (1<<(bit_num-SIZE));
18     else {
19         init_state ^= (1<<(bit_num+SIZE));
20         init_state ^= (1<<(bit_num-SIZE));
21     }
22     if(y==0)
23         init_state ^= (1<<(bit_num+1));
24     else if(y==3)
25         init_state ^= (1<<(bit_num-1));
26     else {
27         init_state ^= (1<<(bit_num+1));
28         init_state ^= (1<<(bit_num-1));
29     }
30     return init_state;
31 }
32 
33 void 
34 dfs(long state, int depth, int count)
35 {
36     if(state==END_BLACK || state==END_WHITE) {
37         min = count < min ? count : min;
38         return;
39     }
40     if(depth >= BIT_MAX || count >= min)
41         return;
42     dfs(state, depth+1, count);
43     dfs(flip(state, depth), depth+1, count+1);
44 }

2. 宽度优先搜索
 1 #define SIZE 4
 2 #define BIT_MAX 16
 3 const int END_BLACK = 0;
 4 const int END_WHITE = (1<<(BIT_MAX))-1;
 5 /* up, down, left, right */
 6 const int dx[] = {-1100};
 7 const int dy[] = {00-11};
 8 const int idx_diff[] = {-SIZE, SIZE, -11};
 9 struct State {
10     long state;
11     int count; /* minimum number of rounds needed to reach 'state' */
12 };
13 struct State queue[1<<BIT_MAX];
14 int visited[1<<BIT_MAX];
15 int head, tail;
16 long state; /* the low 16 bits represents the current state */
17 
18 int
19 is_valid(int x, int y)
20 {
21     return (x>=0 && x<SIZE && y>=0 && y<SIZE);
22 }
23 
24 /*
25  * tricky of bit-operation
26  * 1 ^ x = ~x
27  * 0 ^ x = x
28  */
29 long
30 flip(long state, int x, int y)
31 {
32     int i, index = x*SIZE + y;
33     state ^= (1<<index);
34     for(i=0; i<4; i++) {
35         if(is_valid(x+dx[i], y+dy[i]))
36             state ^= (1<<(index+idx_diff[i]));
37     }
38     return state;
39 }

posted on 2010-07-05 10:51 simplyzhao 阅读(109) 评论(0)  编辑 收藏 引用 所属分类: B_搜索


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


导航

<2010年7月>
27282930123
45678910
11121314151617
18192021222324
25262728293031
1234567

统计

常用链接

留言簿(1)

随笔分类

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜