POJ 1143 Number Game

来源:互联网 发布:中网数据股份有限公司 编辑:程序博客网 时间:2024/05/16 17:33

http://blog.csdn.net/zhengweihit/article/details/5799427

http://wenku.baidu.com/view/e747a907e87101f69e319507.html

题目大意:Christine和Matt玩一个游戏.游戏的规则如下:一开始有一列数字(2~20),有的被列出,有的没有列出.从Christine开始,两人轮流划去一个已被列出的数字.每划去一个数字,其他的所有的能被不在这个数列的数字的两两整线性表示的数也自动从数列中退出.到最后,轮到某人而此时数列中没有元素时,这个人就输了.
规定:winning move能将对手置于losing position的决策;而losing position不存在任何winning move的序列.

解题大体思路,定义输入N(N<=20)个数字为一个状态,扫描这些输入的数字,假设选择数字num(扫描到num)后,如果当前状态有数字可选 并且 选择num后搜索剩下的数字组成的状态为没有数字可选,则选择的数字num为winning move.

N(N<=20)个数字组成的状态,想办法寻找能对应这个状态的hash函数,于是可以有一个20位的数(unsigned int 的低20位)表示,这位为1表示这位在输入数字中,为0表示不在输入数字中。则可定义一个数组record表示状态(有数字可选、没有数字可选、不确定),数组大小为(1<<20),数组的每一个下标是一个状态(表示一组输入),下标对应的值为状态。

巧妙的是这个数组在每次测试时候不用重新初始化,上一次的结果对这次的测试是有用的。也就是本次测试数字如果为2 5,第二次还是2 5,那程序可以直接得出结果了。原因是2 5对应的二进制为000000000000000000001001,因为数字1被排除,所以状态位的第0位表示是否数字2有效,是数组record的下标,读取值就可以知道是不是winning move。程序边运行出结果边填补record的所有内容,所有状态都测试完成后所有结果就都存在record里面了。

#include <iostream>#include <cstdio>#include <cstring>using namespace std;const int maxn = 21;int record[1 << maxn];inline unsigned int mapState(bool *s);bool dfs(bool *s, int pos); //表示选走了第pos的数后,对方是输是赢,对方输返回false, 对方赢返回true int main(){int t = 1;int n;bool source[maxn];while(true){scanf("%d", &n);if(0 == n)break;memset(source, 0, sizeof(source));for(int i = 0; i < n; i++){int val;scanf("%d", &val);source[val] = true;}unsigned int index = mapState(source);int c = 0;int res[maxn];for(int i = 2; i < maxn; i++){if(source[i] && !dfs(source, i))res[c++] = i;}printf("Test Case #%d\n", t++);if(0 == c){record[index] = -1;printf("There's no winning move.\n");}else{printf("The winning moves are: ");for(int i = 0; i < c; i++)printf("%d ", res[i]);printf("\n");}printf("\n");}return 0;}inline unsigned int mapState(bool *s){unsigned int index = 0;for(int i = 2; i < maxn; i++){if(s[i])index |= 1;index <<= 1;}return (index >> 1);}bool dfs(bool *s, int pos){bool cur[maxn];memcpy(cur, s, maxn);cur[pos] = false;for(int i = 2; i + pos < maxn; i++){if(!cur[i])cur[i + pos] = false;}unsigned int index = mapState(cur);if(record[index] > 0)return true;else if(record[index] < 0)return false;for(int i = 2; i < maxn; i++){if(cur[i] && !dfs(cur, i)){record[index] = 1;return true;}}record[index] = -1;return false;}



原创粉丝点击