约瑟夫环问题

第一种方法:递归(可跑1e9)
记 f(n) 为大小为 n ,间隔为 1 约瑟夫环的答案.
当 n 为偶数时:
答案为 2 f ( n / 2 ) − 1
当 n 为奇数时:
答案为 2 f ( n / 2 ) + 1

#include<iostream>
using namespace std;
int gui(int n)
{
	if(n<=2) return 1;
	else if(n%2==0) return 2*gui(n/2)-1;
	else return 2*gui(n/2)+1;
}
int main()
{
	int t,n;
	cin>>t;
	for(int i=1;i<=t;++i)
	{
		cin>>n;
		cout<<gui(n)<<endl;
	}
	return 0;
} 

第二种方法:用链表模拟(跑不到1e7)

#include<iostream>
#include<cstdio>
using namespace std;
inline int read()
{
    int s = 0, w = 1; char ch = getchar();
    while(ch < '0' || ch > '9'){ if(ch == '-') w = -1; ch = getchar();}
    while(ch >= '0' && ch <= '9') s = s * 10 + ch - '0', ch = getchar();
    return s * w;
} 
struct node{
	int data;
	node *next;
};
int main()
{
	int n,t;
	cin>>t;
	for(int j=1;j<=t;++j)
	{
		node *head,*q,*p;
		cin>>n;
		for(int i=1;i<=n;++i)
		{
			p=new node;
			p->data=i;
			if(i==n)
			p->next=head;  //首尾相接
			else
			p->next=NULL;
			if(i==1) head=p;
			else q->next=p;
			q=p;
		}
		p=head;
		while(n>1)
		{
			p->next=p->next->next;   //做删除节点的操作
			p=p->next;
			n--;	
		}
		cout<<p->data<<endl;
	}
	return 0;
} 

第三种方法:打表找规律(可跑1e9)

#include<iostream>
using namespace std;
typedef long long ll;
int main()
{
	ll t;
	ll n;
	cin>>t;
	for(int i=1;i<=t;++i)
	{
		cin>>n;
		if(n==1) cout<<0<<endl;
		else if(n==2) cout<<1<<endl;
		else if(n==3) cout<<3<<endl;
		else
		for(ll i=3,j=4;;i+=j,j*=2)
		{
			//cout<<i<<" "<<j<<endl;
			if(i==n)
			{
				cout<<n<<endl;
				break;
			}
			if(i>n)
			{
				j/=2;
				i-=j;
				n-=i;
				//cout<<i<<" "<<j<<endl;
				ll ans=n%j*2-1;
				cout<<ans<<endl;
				break;
			}
		}
	}
	return 0;
}

规律:
从2开始
1,3---------2个
1,3,5,7---------4个
1,3,5,7,9,11,13,15------------8个
1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31---------------16个
。。。。。。。。。。。。。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值