zoukankan      html  css  js  c++  java
  • 使用链表实现Josephus环问题

    分析:先创建一个有total个结点的链表,然后头尾相连,构成一个环形链表。从第一个结点开始数到第m个结点,从链表中删除对应结点,表示小孩出圈。然后再从被删除结点的下一个结点重新开始计数,直到链表中剩下最后一个结点。

    #include <stdlib.h>
    #include 
    <stdio.h>
    #define LEN sizeof(struct child)
    struct child 
    {
        
    int num;
        
    struct child *next;
    };

    void main()
    {
        
    struct child *create(int num);
        
    int count(struct child *head,int total,int m);
        
    struct child *head;
        
    int total,m,n;
        printf(
    "please input total and start:");
        
    do 
        {
            scanf(
    "%d%d",&total,&m);
        } 
    while(total<2||m<2||m>total);
        head
    =create(total);
        n
    =count(head,total,m);
        printf(
    "\nThe left child is %d\n",n);
    }

    struct child *create(int num)
    {
        
    struct child *p1,*p2,*head;
        
    int i;
        p1
    =(struct child *)malloc(LEN);
        p1
    ->num=1;
        head
    =p1;
        
    for (i=2;i<=num;i++)
        {
            p2
    =(struct child *)malloc(LEN);
            p2
    ->num=i;
            p1
    ->next=p2;
            p1
    =p2;
        }
        p1
    ->next=head;                    //头尾相连
        return head;
    }

    int count(struct child *head,int total,int m)
    {
        
    struct child *p=head,*old;
        
    int i,j;
        
    for (i=1;i<total;i++)            //循环次数
        {
            
    for (j=1;j<m;j++)            //循环个数
            {
                old
    =p;
                p
    =p->next;
            }
            printf(
    "%3d",p->num);
            old
    ->next=p->next;
            free(p);
            p
    =old->next;
        }
        
    return p->num;
    }
  • 相关阅读:
    题解 BZOJ1026 & luogu P2657 [SCOI2009]windy数 数位DP
    BZOJ 1867 [Noi1999]钉子和小球 DP
    P5057 [CQOI2006]简单题 前缀异或差分/树状数组
    P2051 [AHOI2009]中国象棋 大力DP
    P4208 [JSOI2008]最小生成树计数
    BZOJ 2440 [中山市选2011]完全平方数 二分+容斥
    Luogu P1951 收费站_NOI导刊2009提高(2) 二分 最短路
    Luogu P3527 [POI2011]MET-Meteors 整体二分
    Luogu P4109 [HEOI2015]定价 贪心
    Luogu P2114_[NOI2014]起床困难综合症 贪心
  • 原文地址:https://www.cnblogs.com/qixin622/p/1238204.html
Copyright © 2011-2022 走看看