17个人手拉手排队,用递归算,数到3出列.

来源:百度知道 编辑:UC知道 时间:2024/05/25 13:09:11
例: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
1 的编号是0,2的编号是1,3的编号是2(...),从编号0开始数,数到3出列,第一次是 4 出来了,依次类推,用递归算。 明白人来, 速度。 谢谢了.

会了

没用递归写过 不喜欢递归 太慢 上边的是原算法 改了一下递归
#include <iostream>
using namespace std;
#define offset 3
#define n 18
int main()
{
int a[n],i,pos=0,length=n-1;
for(i=0;i<n-1;i++)
a[i]=i+1;
while(length)
{
a[length]=a[(pos+offset)%length];
pos=(pos+offset)%length;
for(i=pos;i<length;i++)
a[i]=a[i+1];
length--;
}
for(i=n-1;i>0;i--)
cout<<a[i]<<' ';
return 0;
}
////////////////////////////////////////
#include <iostream>
using namespace std;
#define offset 3
#define n 18
void jos(int *a,int length,int pos)
{
if(!length) return;
a[length]=a[(pos+offset)%length];
pos=(pos+offset)%length;
for(int i=pos;i<length;i++)
a[i]=a[i+1];
cout<<a[length]<<' ';
jos(a,length-1,pos);
}
int main()
{
int a[n],i,pos=0,le