信息学奥赛一本通T2037约瑟夫问题(动态链表)

咳咳咳

好久没写CSDN了

本蒟蒻写的这些东西应该没人看吧(确信)

好了好了,进入正题(传送锚点->题目

本题思路十分简单:

1.传统数组法(我们此处只讲动态链表的思路)

当然,如过你是比我还弱的蒟蒟蒻请去看其他各路大神的数组题解

那就直接放上数组的AC代码了

欸,我这不是写动态链表方法的吗?

2.动态链表

首先,建立一个动态链表

如下:

#include<bits/stdc++.h>
using namespace std;
struct node{
	int num;
	node *pre;
	node *next;
};//建立链表结构体
int main()
{
	int n,m;
	cin>>n>>m;
	node *head=NULL;
	node *tail=NULL;
    //表头表尾(其实表尾并无卵用)
	node *temp=NULL;
    //记录上一个节点
	for(int i=1;i<=n;i++)
	{
		node *t=new node;//建立一个动态链表节点
		if(head==NULL){//记录表头
			head=t;
		}
		t->num=i;//记录号码
		t->pre=temp;//前驱
		t->next=NULL;//后继
		if(temp!=NULL){//如果前一个不是空的
			temp->next=t;//将前一个的后继指向当前节点
		}
		temp=t;//将前一个指向当前节点
		if(i==n){
			tail=t;
			head->pre=tail;
			tail->next=head;
		}//链接表头表尾
	}

 然后是叫号踢人(doge) 

    int ns=n;//剩余人数
	int pt=0;//目前叫号
	node *p=head;//拿一个指针方便遍历
	while(ns!=0){//人数不等于0
		pt++;//叫号
		if(pt==m)//号数符合
		{
			p->pre->next=p->next;
			p->next->pre=p->pre;
            //断链(踢人)
			pt=0;//重置号数
			ns--;//人数减一
			cout<<(p->num)<<" ";//输出序号
		}
		p=p->next;//移动遍历指针
	}
	return 0;
}

有耐心看到最后的好人们,就能拿到……

《无注释全代码》

#include<bits/stdc++.h>
using namespace std;
struct node{
	int num;
	node *pre;
	node *next;
};
int main()
{
	int n,m;
	cin>>n>>m;
	node *head=NULL;
	node *tail=NULL;
	node *temp=NULL;
	for(int i=1;i<=n;i++)
	{
		node *t=new node;
		if(head==NULL){
			head=t;
		}
		t->num=i;
		t->pre=temp;
		t->next=NULL;
		if(temp!=NULL){
			temp->next=t;
		}
		temp=t;
		if(i==n){
			tail=t;
			head->pre=tail;
			tail->next=head;
		}
	}
	int ns=n;
	int pt=0;
	node *p=head;
	while(ns!=0){
		pt++;
		if(pt==m)
		{
			p->pre->next=p->next;
			p->next->pre=p->pre;
			pt=0;
			ns--;
			cout<<(p->num)<<" ";
		}
		p=p->next;
	}
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值