設有n座山,計算機與人為比賽的雙方,輪流搬山。規定每次搬山的數止不能超 過k座,誰搬最後一座誰輸。游戲開始時。計算機請人輸入山的總數(n)和每次允許搬山的最大數止(k)。然後請人開始,等人輸入了需要搬走的山的數目後,計算機馬上打印出它搬多少座山,並提示尚余多少座山。雙方輪流搬山直到最後一座山搬完為止。計算機會顯示誰是贏家,並問人是否要繼續比賽。若人不想玩了,計算機便會統計出共玩了幾局,雙方勝負如何。
*問題分析與算法設計
計算機參加游戲時應遵循下列原則:
1) 當:
剩余山數目-1<=可移動的最大數k 時計算機要移(剩余山數目-1)座,以便將最後一座山留給人。
2)對於任意正整數x,y,一定有:
0<=x%(y+1)<=y
在有n座山的情況下,計算機為了將最後一座山留給人,而且又要控制每次搬山的數目不超過最大數k,它應搬山的數目要滿足下列關系:
(n-1)%(k+1)
如果算出結果為0,即整除無余數,則規定只搬1座山,以防止冒進後發生問題。
按照這樣的規律,可編寫出游戲程序如下:
#include
int main()
{
int n,k,x,y,cc,pc,g;
printf("More Mountain Game\n");
printf("Game Begin\n");
pc=cc=0;
g=1;
for(;;)
{
printf("No.%2d game \n",g++);
printf("---------------------------------------\n");
printf("How many mpuntains are there?");
scanf("%d",&n);
if(!n) break;
printf("How many mountains are allowed to each time?");
do{
scanf("%d",&k);
if(k>n||k<1) printf("Repeat again!\n");
}while(k>n||k<1);
do{
printf("How many mountains do you wish movw away?");
scanf("%d",&x);
if(x<1||x>k||x>n) /*判斷搬山數是否符合要求*/
{
printf("IIIegal,again please!\n");
continue;
}
n-=x;
printf("There are %d mountains left now.\n",n);
if(!n)
{
printf("...............I win. You are failure...............\n\n");cc++;
}
else
{
y=(n-1)%(k+1); /*求出最佳搬山數*/
if(!y) y=1;
n-=y;
printf("Copmputer move %d mountains away.\n",y);
if(n) printf(" There are %d mountains left now.\n",n);
else
{
printf("...............I am failure. You win..................\n\n");
pc++;
}
}
}while(n);
}
printf("Games in total have been played %d.\n",cc+pc);
printf("You score is win %d,lose %d.\n",pc,cc);
printf("My score is win %d,lose %d.\n",cc,pc);
}
*