線性表及其應用——約瑟夫環問題

來源:互聯網
上載者:User

題目:約瑟夫環(Joseph)

① 問題描述:編號為1到n的n個人,按順時針方向圍成一個環,每人都持有一個密碼(正整數)。任選一個正整數作為報數的上限(設為m),從第一個人開始按順時針方向從1開始順序報數,當報到m時暫停報數,並將報數為m的人輸出,同時將他的密碼作為新的m值,繼續從1開始重新報數,直到m並輸出。如此重複,直到全部人員都從隊列中輸出。編寫程式,求出該出列順序。

#include <stdio.h>#include <stdlib.h>int m,n;typedef struct LNode{    int IDCode;    int PWD;    struct LNode *next;} LNode;LNode *LinkList;void creatJoseph(int num,int PSW[]){    LNode *L=(LNode*)malloc(sizeof(LNode)),*LL;    for(int i=0; i<num; i++)    {        scanf("%d",&PSW[i]);        L->IDCode=i+1;        L->PWD=PSW[i];        if(i==0) LinkList=L;        L->next=(LNode *)malloc(sizeof(LNode));        if(i==num-1) L->next=LinkList;        L=L->next;    }}void printIDCode(LNode *t,int k){    t=LinkList;    LNode *t1;    if(k>n) k%=n;    while(n--)    {        if(n==0)        {            printf("%d\t\n",t->IDCode);            break;        }        if(k!=1)        {            for(int i=1; i<=k-2; i++)            {                t=t->next;            }        }        else        {            int tID=t->IDCode;            for(;;)            {                t=t->next;                if(t->next->IDCode==tID) break;            }        }        printf("%d\t",t->next->IDCode);        k=t->next->PWD;        if(k>n) k%=n;        t1=t->next;        t->next=t->next->next;        t=t->next;        free(t1);    }}int main(){    //freopen("in.txt","r",stdin);    LNode *L;    int PSW[30];    printf("輸入人員數n\n");    scanf("%d",&n);    printf("輸入初始密碼m\n");    scanf("%d",&m);    creatJoseph(n,PSW);    L=LinkList;    printIDCode(L,m);    printf("以上是我的的運行結果\n");    return 0;}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.