zoukankan      html  css  js  c++  java
  • 约瑟夫环

     1 #include <iostream>
     2 #include <stdlib.h>
     3 
     4 using namespace std;
     5 
     6 typedef struct LinkNode{
     7     int data;
     8     struct LinkNode* next;
     9 }JosephuNode;
    10 
    11 
    12 int Josephu(int n, int m)
    13 {
    14 
    15     //creat
    16     JosephuNode *head, *tail;
    17     head = tail = (JosephuNode*) malloc(sizeof(JosephuNode));;
    18 
    19     for(int i = 1; i < n; i++)
    20     {
    21         tail->data = i;
    22         tail->next = (JosephuNode*)malloc(sizeof(JosephuNode));
    23         tail = tail->next;
    24     }
    25     tail->data = n;
    26     tail->next = head;
    27 
    28 
    29     //loop
    30     while(tail != head)
    31     {
    32         for(int j = 1; j < m; ++j)
    33         {
    34             tail = head;
    35             head = head->next;
    36         }
    37         tail->next = head->next;
    38         cout<<head->data<<endl;
    39         free(head);
    40         head = tail->next;
    41     }
    42 
    43     int last = head->data;
    44     free(head);
    45     head = tail = NULL;
    46 
    47     return last;
    48 }
    49 
    50 
    51 int main()
    52 {
    53     int n,m;
    54     cout<<"input n and m:"<<endl;
    55     cin>>n>>m;
    56     int last = Josephu(n, m);
    57     cout<<"Last number is:"<<last<<endl;
    58 
    59 
    60     return 0;
    61 }
    View Code
     1 #include<iostream>
     2 #include<list>
     3 #include<fstream>
     4 using namespace std;
     5 int main()
     6 {
     7     int m,n,temp,i,j;
     8     FILE *out;
     9     out=fopen("out","w");
    10     cout<<"input n and m:"<<endl;
    11     cin>>n>>m;
    12     int a[n];
    13     for(i=1;i<=n;i++)
    14         a[i]=i;
    15     a[0]=0;
    16     i=0;
    17     temp=n;
    18     while(temp)
    19     {
    20         for(j=0;j<m;)
    21         {
    22             i=(i)%n+1;
    23             if(a[i]!=0)
    24                 j++;
    25 
    26         }
    27 
    28         cout<<a[i]<<endl;
    29         fprintf(out, "%d
    ", a[i]);
    30         a[i]=0;
    31         temp--;
    32 
    33     }
    34     fclose(out);
    35 
    36 
    37     return 0;
    38 }
    39 //数组
    View Code
  • 相关阅读:
    浅谈组装主机的一些注意问题2
    浅谈组装主机的一些注意问题1
    浅谈组装主机的一些注意问题
    openGL中的原理理解1---一个视图需要支持OGL需要配置,GLenbalView的理解
    OpenGL中常用的函数
    MFC中的DLL、LIb文件的创建、使用
    MFC中的多线程
    MFC中的一般经验之谈5
    算法时间复杂度和NP问题简介
    如何搜索高质量论文
  • 原文地址:https://www.cnblogs.com/zhenzhenhuang/p/5461057.html
Copyright © 2011-2022 走看看