您的位置:首页 > 编程语言 > C语言/C++

取石子(好学的C++)

2013-11-29 21:58 197 查看
巴什博奕(Bash Game)只有一堆n个物品,两个人轮流从这堆物品中取物,规定每次至少取一个,最多取m个。最后取光者得胜。

显然,如果n=m+1,那么由于一次最多只能取m个,所以,无论先取者拿走多少个,后取者都能够一次拿走剩余的物品,后者取胜。因此我们发现了如何取胜的 法则:如果n=(m+1)r+s,(r为任意自然数,s≤m),那么先取者要拿走s=n/(m+1)个物品,如果后取者拿走k(≤m)个,那么先取者再拿走m+1-k个, 结果剩下(m+1)(r-1)个,以后保持这样的取法,那么先取者肯定获胜。总之,要保持给对手留下(m+1)的倍数,就能最后获胜。

#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
int total, n, m;

cout << "Welcome to NIM. Pick a staring total: ";
cin >> total;
cout << "请输入你想减去值的范围最大值。";
while (total <= 0)
{
cout << "请输入一个大于0的数: ";
cin >> total;
if (total > 0)
{
break;
}

}
while (true)
{
//通过判断,做出最好的选择,并打印出结果。

if ((total % m+1 == m))
{
total = total - 2;
cout << "I am subtacting 2." << endl;
}
else
{
total --;
cout << "I am subtacting 1." << endl;
}
cout << "New total is " << total << endl;
if (total == 0)
{
cout << "I win!" << endl;
break;
}

//获得用户的输入,必须是1或者2;

cout << "Enter num to subtract (1 or 2):";
cin >> n;
while (n < 1 || n > 2)
{
cout << "Input must be 1 or 2." << endl;
cout << "Re-enter. ";
cin >> n;
}
total = total - n;
cout << "New total is " << total << endl;
if (total == 0)
{
cout << "You win." << endl;
break;
}
}

system("PAUSE");
return EXIT_SUCCESS;
}


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