圆桌问题

圆桌问题

问题描述:
圆桌上围坐着2n个人。其中n个人是好人,另外n个人是坏人。如果从第一个人开始数数,数到第m个人,则立即处死该人;然后从被处死的人之后开始数数,再将数到的第m个人处死……依此方法不断处死围坐在圆桌上的人。试问预先应如何安排这些好人与坏人的座位,能使得在处死n个人之后,圆桌上围坐的剩余的n个人全是好人。

输入说明:
输入:好人和坏人的人数n(<=32767)、步长m(<=50);

输出说明:
输出2n个大写字母,‘G’表示好人,‘B’表示坏人。

输入范例:
52 6

输出范例:
BGGBGBGGBBBBGGGGBBBGBGGBGBBGGBBGBGBBGGGBBBGBGG BBGGBBGBBGGGGBBBBGGBGGBBGBBGGBGBBGGBBBGGBGGBBGGGBBGBGGGBGB

#include<iostream>
using namespace std;

struct ListNode{
	char num;
	int great; 
	struct ListNode  *next;
};

ListNode *createByTail(int count){
	ListNode *head=new ListNode;
	ListNode *p,*p1;
	p=head;
	head->next=NULL;
	int i=1;
	count=count*2;
	while(i<=count){
		p1=new ListNode;
		p1->great=0;
		p1->num='G';
		p->next=p1;
		p=p1;
		i++;
	}
	p->next=head;
	return head;
} 

void josephus(ListNode *head, int m,int n){//步长m,人数 n ,-1为坏人 
    int len=n;
    ListNode *cur=head->next;
    int count=1;
    while(len>0){
        if(count==m){
            if(cur->great!=-1){
                cur->great=-1;
                count=1;
                len--;
                cur=cur->next;
            }else{
                cur=cur->next;
            }
        }else if(count<m){
            if(cur->great!=-1){
                cur=cur->next;
                count++;
            }else{
                cur=cur->next;
            }
        }
        if(cur==head){
            cur=cur->next;
        }
    }
    ListNode *p;
    p=head->next;
    int c=1;
    while(p!=head){
        if(p->great==-1){
            p->num='B';
        }
        if(c==50){
            cout<<p->num<<endl;
            c=1;
        }else{
            cout<<p->num;
            c++;
        } 
        p=p->next;
    }
}

int main(){
	int count,len;
	cin>>count>>len;
	ListNode *head=createByTail(count);
	josephus(head,len,count);

}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值