問題描述(OJ題目)
約瑟夫環(約瑟夫問題)是一個數學的應用問題:已知n個人(以編號1,2,3...n分別表示)圍坐在一張圓桌周圍。從編號爲k的人開始報數,數到m的那個人出列;他的下一個人又從1開始報數,數到m的那個人又出列;依此規律重複下去,直到圓桌周圍的人全部出列。
數組實現
用數組a[i]記錄第i個人的狀態,如果出局轉態爲1,反之爲0。
每次i == n+1時(下標從1開始)則i =1,從頭開始。
用cnt記錄當前的報數。
#include<stdio.h>
#include<string.h>
int main()
{
int a[201];
int n, m;
while(scanf("%d%d",&n,&m)!=EOF)
{
memset(a, 0,sizeof(a));
int dead = 0;//現在已經退出的人
int cnt = 0; //每輪的報數
int index = 1;//數組的下標
while(dead!=n)
{
if(a[index]==0)
{
cnt++;
if(cnt==m)
{
printf("%d\n",index);
a[index] = 1;//標記退出的人
cnt = 0;//歸0
dead++;//退出的人數+1
}
}
index++;
if(index == n+1)
index = 1;
}
}
return 0;
}
/*
5 3
3
1
5
2
4
*/
循環鏈表實現
鏈表實現就不需要上面的三個變量,只需要建立循環鏈表,記錄第m報數的前一個人,每次出局後,將此人刪除。
#include<stdio.h>
#include<string.h>
struct node
{
int data;
node *next;
};
int main()
{
int n, m;
while(scanf("%d%d",&n,&m)!=EOF)
{
node *head, *now, *temp;
now = new node;//第一個結點,沒有頭結點
head = now;
now->data = 1;
now->next = NULL;
for(int i=2; i<=n; i++)
{
temp = new node;
temp->data = i;
now->next = temp;
now = temp;
}
now->next = head;//形成循環鏈表
int dead = 0;//退出去的人
node *pre;
while(head->next!=head)
{
for(int i=1; i<m; i++)
{
pre = head;//記錄退出的前一個人
head = head->next;
}
printf("%d\n",head->data);//第M個人
//刪除退出的人
pre->next = head->next;
delete(head);//刪除head指向的元素
head = pre->next;
}
//最後一個人
printf("%d\n",head->data);
}
}