zoukankan      html  css  js  c++  java
  • 【C++】约瑟夫环(数组+链表)

    基于数组:

    #include<iostream>
    #include<cstring>
    #include<cstdlib>
    using namespace std;
    
    int *a;
    int *vis;
    
    bool isfull(int m)
    {
        for(int i=0;i<m;i++)
        {
            if(!vis[i])
                return false;
        }
        return true;
    }
    
    void john(int m,int n)
    {
        int p=m-1;
        while(!isfull(m))
        {
            int left=n;
            while(left>0)
            {
                p=(p+1)%m;
                if(!vis[p])
                {
                    left--;
                }
                cout<<vis[p];
            }
            vis[p]=1;
            cout<<":"<<a[p]<<endl;
        }
    }
    
    int main()
    {
        int m,n;
        while(scanf("%d %d",&m,&n)&&m&&n)
        {
            a=(int *)malloc(m*sizeof(int));
            for(int i=0;i<m;i++)
                a[i]=i+1;
            vis=(int *)malloc(m*sizeof(int));
            for(int i=0;i<m;i++)
                vis[i]=0;
            
            john(m,n);
        }
        
        return 0;
    }

    基于链表:

    #include<iostream>
    using namespace std;
    
    struct node
    {
        int data;
        node *next;
    };
    
    node *head;
    
    void john(int m,int n)
    {
        node *p=head;
        node *r=head->next;
        while(r->next!=head)
            r=r->next;
        while(p)
        {
            if(p->next==p)
            {
                cout<<p->data<<endl;
                return ;
            }
            int left=n;
            while(left>1)
            {
                left--;
                p=p->next;
                r=r->next;
            }
            cout<<p->data<<endl;
            r->next=p->next;
            delete p;
            p=r->next;
        }
    }
    
    int main()
    {
        int m,n;
        while(scanf("%d %d",&m,&n)&&m&&n)
        {
            head=new node();
            head->data=1;
            node *p=head;
            int a=2;
            while(a<=m)
            {
                node *t=new node();
                t->data=a;
                p->next=t;
                p=p->next;
                a++;
            }
            p->next=head;//形成环 
            /*
            p=head->next;
            while(p!=head)
            {
                cout<<p->data<<endl;
                p=p->next;
            }
            */
            john(m,n);
        }
        
        return 0;
    }

    运行示例:

    tz@HZAU

    2019/3/12

  • 相关阅读:
    主外键 子查询
    正则表达式
    css3 文本效果
    css3 2d
    sql 基本操作
    插入 视频 音频 地图
    j-query j-query
    document
    js dom 操作
    js
  • 原文地址:https://www.cnblogs.com/acm-icpcer/p/10520065.html
Copyright © 2011-2022 走看看