1561 - 围圈报数

通过次数

0

提交次数

0

时间限制 : 1 秒 内存限制 : 32 MB
N 个人围成一圈顺序编号,从1 号开始按1、2、3 顺序报数,报3 者退出圈外,其余的人再从1、2、3 开始报数,报3 的人再退出圈外,依次类推。请按退出顺序输出每个退出人的原序号。要求使用环行链表编程。

题目输入

输入第一行为整数m表示有m组测试数据,接下来m行每行一个整数N,N不超过50。

题目输出

输出m行,每行表示题目所求,用空格隔开。

输入/输出样例

输入格式

1
4

输出格式

3 2 4 1

C语言解答

#include<stdio.h>
#include<stdlib.h>
typedef struct Node
{
	int data;
	struct Node *next;
}Node;
int main()
{
	int m,n;
	scanf("%d",&n);
	for(int l=1;l<=n;l++)
	{
		scanf("%d",&m);
		int k=1;
		Node *c,*s,*r,*p;
		c=(Node *)malloc(sizeof(Node));
		c->next=NULL;
		r=c;
		p=c;
		for(int j=1;j<=m;j++)
		{
			s=(Node *)malloc(sizeof(Node));
			s->data=k++;
			r->next=s;
			r=r->next;
		}
		r->next=p->next;
		p=p->next;
		int count=1;
		while(p->next->data!=p->data)
		{
			if(count%3==0)
			{
				printf("%d ",p->data);
				p->data=p->next->data;
				p->next=p->next->next;
				count++;
				continue;
			}
			p=p->next;
			count++;
		}
		printf("%d\n",p->data);
		/*for(int i=0;i<=m+10;i++)
		{
			printf("%d ",p->data);
			p=p->next;
			printf("\n");
		}*/
	}
	//system("pause");
	return 0;
}

C++解答

#include <iostream>
#include <malloc.h>
#include <cstdio>
using namespace std;

typedef struct node
{
    int num;
    struct node *next;
} LNode;

int main()
{
    //freopen("test.in", "r", stdin);
    //freopen("test.out", "w", stdout);
    int t;
    cin >> t;
    while (t--)
    {
        LNode *head,*p,*q;
        int N;
        cin>>N;
        p=(LNode*)(malloc(sizeof(LNode)));
        p->num=1;
        head=p;
        for(int i=1; i<N; i++)
        {
            p->next=(LNode*)(malloc(sizeof(LNode)));
            p=p->next;
            p->num=i+1;
        }
        p->next=head;
        p=head;
        while(p->next!=p)
        {
            q=p->next;
            p=q->next;
            q->next=p->next;
            cout<<p->num<<" ";
            delete p;
            p=q->next;
        }
        cout<<p->num<<endl;
        delete p;

    }
    return 0;
}

Java解答

public class Main {
            public static void main(String[] args) { 
              java.util.Scanner in= new java.util.Scanner(System.in) ;
            while(in.hasNextInt()){
            int a = in.nextInt();
            for(int i=0;i<a;i++) {
            int b = in.nextInt();
            int[] number =new int[b];
            int m=1;
            for(int j=0;j<b;j++){
                number[j]=m;
                m++;
            }
            int c=0,count=0;
            while(c!=b){
            for(int j=0;j<b;j++){
                if(number[j]!=0) count++;
                if(count==3) {
                    System.out.print(j+1);c++;
                    if(c<b) System.out.print(" ");
                    number[j]=0;count=0;
            }
        } 
        }System.out.println();
    }
}
}
}