JosePhu Problem

本文通过使用链表数据结构解决了约瑟夫环问题。具体场景为飞机上共有30名乘客,包括15名美国人和15名日本人,但由于风暴来袭,飞机只能承载15名乘客。所有乘客围成一圈并从1开始编号到7,每数到7的人将离开飞机,直至只剩15人。文章提供了一个C++实现方案。

      There are 15 American and 15 Japanese in the plane. However, it cann't takes more than 15 passengers because of the storm. At last they made a decision about that, all of them stand around as a circle and numbering to 7 from 1, the number one 7 have to leave the plane and numbering repeatedly from 1 again. Please design an order which let all of the American could still be safe in the plane.

#include <iostream>
#include 
<string>
using namespace std;

typedef 
struct Linklist
ExpandedBlockStart.gifContractedBlock.gif
{
    
int m_date;
    Linklist 
*pNext;
}
Node, *List;

void Josephus(Node *head, int start, int interval, int nums)
ExpandedBlockStart.gifContractedBlock.gif
{
    
if(!head)
        
return;

    Node 
*temp = head;
    Node 
*temp2 = NULL;

    cout
<<"Count From "<<start<<endl;
    cout
<<"interval is "<<interval<<endl;

    
while(start - 1)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
{
        temp 
= temp->pNext;        
    }

      
    
while(nums)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
{
        
for(int i = 1; i < interval - 1; i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            temp 
= temp->pNext;
        }


        temp2 
= temp->pNext;
        cout
<<temp2->m_date<<endl;
        temp
->pNext = temp2->pNext;
        delete(temp2);
        temp2 
= NULL; 
        temp 
= temp->pNext;
        nums
--;
    }
   
}

void main()
ExpandedBlockStart.gifContractedBlock.gif
{
    
int counts = 30;
    Node 
*head = NULL;
    Node 
*temp = NULL;
    
for(int i = 1; i <= counts; i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
{
        Node 
*newNode = new Node;
        newNode
->m_date = i;
        
if(i == 1)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            head 
= newNode;
            temp 
= head;
        }

        
else
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            temp
->pNext = newNode;
            temp 
= temp->pNext;
        }

    }

    temp
->pNext = head;

    Josephus(head, 
1230);
    cin
>>counts;
}

 

转载于:https://www.cnblogs.com/jackill/archive/2009/06/08/1498920.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值