约瑟夫环问题(线性表)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_43244265/article/details/102758954

约瑟夫环是一个数学的应用问题:已知n个人(以编号1,2,3…n分别表示)围坐在一张圆桌周围。从编号为k的人开始报数,数到m的那个人出列;他的下一个人又从1开始报数,数到m的那个人又出列;依此规律重复下去,直到圆桌周围的人全部出列。
输入
8 1 3 (n=8 k=1 m=3 )
输出
7 (剩下的那个)
样例输入
8 3 1
样例输出
7
思路:循环链表
AC代码:

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn=10000;
int a[1000010],b[100010];
template<class T>
struct node
{
   int data;
    node<T>* next;
};
template<class T>
class lian
{
   node<T> *first;
   int l;
   public:
   lian();
   lian(T a[],int n);
   void show();
   void weishan(int k,int m);
};
template <class T>
lian<T>::lian()
{
    first=new node<T>;
    first->next=NULL;
}
template <class T>
lian<T>::lian(T a[],int n)
{
    first=new node<T>;
    node<T> *r;
    r=first;
     node<T> *s;
    for(int i=0;i<n;i++)
    {
        s=new node<T>;
        s->data=a[i];
        r->next=s;
        r=s;
    }
    r->next=first->next;
    l=n;
}

template <class T>
void lian<T>::show()
{
    node<T> *p;
    p=first->next;
    int t=0;
    while(t<l)
    {
        cout<<p->data<<" ";
        p=p->next;
        t++;
    }
    cout<<endl;
}
template <class T>
void lian<T>::weishan(int k,int m)
{
    node<T> *p=first,*q,*h;
    int ii=0;
    while(1)
    {
        if(ii==k-1) break;
        p=p->next;
        ii++;
    }
    while(l>1)
    {
        for(int i=1;i<m;i++)
    {
        p=p->next;
    }
    q=p->next;
    if(first->next=q)
    {
        first->next=q->next;
    }
    p->next=p->next->next;
    //cout<<q->data<<endl;
    delete q;
    l--;
    }
}
int main()
{
   int n,k,m;
   ios::sync_with_stdio(false);
   cin>>n>>k>>m;
   for(int i=1;i<=n;i++)
   {
       a[i-1]=i;
   }
   lian<int> h(a,n);
   h.weishan(k,m);
   h.show();
}

猜你喜欢

转载自blog.csdn.net/weixin_43244265/article/details/102758954