约瑟夫环 (Ver. I - A)

题目描述

N个人坐成一个圆环(编号为1 - N),从第S个人开始报数,数到K的人出列,后面的人重新从1开始报数。问最后剩下的人的编号。

例如:N = 3,K = 2,S = 1。2号先出列,然后是1号,最后剩下的是3号。

要求使用循环链表实现。

输入

测试数据有多组,

每组包括3个数N、K、S,表示有N个人,从第S个人开始,数到K出列。(1 <= N <= 10^6,1 <= K <= 10,  1 <= S <= N)

输出

出列的人的编号

样例输入

13 3 1 3 2 1

样例输出

3 6 9 12 2 7 11 4 10 5 1 8 13 2 1 3

 

#include <iostream>
#include <algorithm>
#define ok 0
#define error -1
using namespace std;

struct Node
{
    int  data;
    Node *next;
    Node(int _data=0, Node *_next=NULL):data(_data),next(_next){}
};

Node *createlist(int n,int *data)
{
    Node *head = new Node;
	Node *s,*tail=head;

    for(int i=0; i<n; i++)
	{
		s = new Node(data[i],NULL);
		tail->next = s;
		tail = s;
	}
	tail->next=head;
	return head;
}

void test(int u)
{
    Node *head,*temp;
	int k,*data,n=u,s;

	cin>>k>>s;
    data = new int[n];
	for(int i=0;i<n;i++)
    {
        data[i]=i+1;
    }
    head = createlist(n,data);
    Node *p=head,*q=head,*z=head;
    int w=s,num=1,x=0;
    while(w--)
    {
        p=p->next;
    }
    while(1)
    {
        if(q->next==p)
            break;
        else
            q=q->next;
    }
    while(1)
    {
        if(p==head)
        {
            p=p->next;
            q=q->next;
            continue;
        }
        if(num==k)
        {
            cout<<p->data<<" ";
            q->next=p->next;
            z=p;
            p=p->next;
            free(z);
            x++;
            if(x==n)
                break;
            num=(num%k)+1;
        }
        else
        {
            p=p->next;
            q=q->next;
            num=(num%k)+1;
        }
    }


    cout<<endl;
}

int main()
{
    int n;
    while(cin>>n)
    {
        test(n);
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值