www.bersaty.com

一道简单的博弈题~

现有21根火柴,两人轮流取,每人每次可取走1- 4根,不可多取,也不能不取,谁取最后一根火柴则谁输。请编写一个程序进行人机对弈,要求人先取,计算机后取;计算机一方为“常胜将军”。

 

从前往后推

(人)       (机)

1        2~5

6        7~10

11      12~15

16      17~20

21

只要人按1,6,11,16,21走,计算机就必定能赢

#include<stdio.h>
int main()
{
	int m,n=21;
	while(1)
	{
		printf("How many sticks do you wish to take(1~4)?");
		scanf("%d",&m);
		n-=m;
		if(n==0)
		{
			printf("You have taken the last stick.\n* * * You lose!");
			break;
		}
		printf(" %d stick left in the pile.\n",n);
		if(n>16)
			m=n-16;
		if(n>11&&n<16)
			m=n-11;
		if(n>6&&n<11)
			m=n-6;
		if(n>1&&n<6)
			m=n-1;
		printf(" computer take %d stick.\n",m);
		n-=m;
		printf(" %d stick left in the pile.\n",n);
	}
	return 0;
}

 

posted @ 2011-10-27 21:11  bersaty  阅读(304)  评论(0编辑  收藏  举报