1. 程式人生 > >約瑟夫環

約瑟夫環

++ const ostream 題目 tex nod 一個 include null

約瑟夫環

一、心得

二、題目及分析

約瑟夫環

三、代碼及結果

1、

 1 #include <iostream>
 2 using namespace std;
 3 
 4 const int n=10,m=4;
 5 int a[n+1]; // 6 
 7 //初始化環 
 8 void initCercle(int a[]){
 9     for(int i=1;i<n;i++){
10         a[i]=i+1;
11     }
12     a[n]=1;
13 }
14 //打印環 
15 void printCercle(int a[]){
16     for
(int i=1;i<=n;i++){ 17 cout<<a[i]<<" "; 18 } 19 cout<<endl; 20 } 21 22 //找輸出節點的前一個節點,然後a[]就好 23 void work(){ 24 int k=n; 25 for(int i=1;i<=n;i++){ 26 //這裏只做了m-1,這裏是三次,因為被刪的節點被跳過了 27 for(int j=1;j<m;j++){ 28 k=a[k]; 29 }
30 cout<<a[k]<<" "; 31 a[k]=a[a[k]]; 32 //cout<<"k:"<<k<<"a[k]:"<<a[k]<<endl; 33 } 34 } 35 36 int main(){ 37 38 initCercle(a); 39 printCercle(a); 40 work(); 41 42 43 return 0; 44 }

2、約瑟夫環(pre)

 1 #include <iostream>
 2
using namespace std; 3 4 const int n=10,m=4; 5 int a[n+1]; // 6 7 //初始化環 8 void initCercle(int a[]){ 9 for(int i=1;i<n;i++){ 10 a[i]=i+1; 11 } 12 a[n]=1; 13 } 14 //打印環 15 void printCercle(int a[]){ 16 for(int i=1;i<=n;i++){ 17 cout<<a[i]<<" "; 18 } 19 cout<<endl; 20 } 21 22 //找輸出節點的前一個節點,然後a[]就好 23 void work(){ 24 int k=n; 25 int pre; 26 for(int i=1;i<=n;i++){ 27 //這裏做了m,這裏是4次 28 for(int j=1;j<=m;j++){ 29 pre=k; 30 k=a[k]; 31 } 32 cout<<a[pre]<<" "; 33 a[pre]=a[a[pre]]; 34 //cout<<"k:"<<pre<<"a[k]:"<<a[pre]<<endl; 35 } 36 } 37 38 int main(){ 39 40 initCercle(a); 41 printCercle(a); 42 work(); 43 44 45 return 0; 46 }

3、約瑟夫環(鏈)

 1 //約瑟夫環(鏈) 
 2 #include <iostream>
 3 using namespace std;
 4 
 5 const int n=10,m=4;
 6 
 7 
 8 struct node{
 9     int data;
10     node *next;
11 }; 
12 node *head=new node;
13 
14 void initList(){
15     head->data=0;
16     head->next=NULL;
17     for(int i=10;i>=1;i--){
18         node *p=new node;
19         p->data=i;
20         p->next=head->next;
21         head->next=p; 
22     }
23 }
24 
25 void printList(){
26     node *p=head->next;
27     while(p){
28         cout<<p->data<<" ";
29         p=p->next;
30     }
31     cout<<endl;
32 }
33 
34 void work(){
35     node *p=head;
36     node *pre;
37     for(int i=1;i<=n;i++){
38         for(int j=1;j<=m;j++){
39             pre=p;
40             p=p->next;
41             if(!p) p=head->next;
42         } 
43         cout<<p->data<<" ";
44         pre->next=p->next;
45     }
46 }
47 
48 
49 int main(){
50     initList();
51     printList();
52     work();
53     return 0;
54 } 

技術分享

約瑟夫環