哎~这个题目得优化下才能AC....

题目: 一天粒粒想到我们实验室玩个小游戏!n个人围成一圈!一起报数!报到第m的时候!那个报m的退出!又从1开始报!依次类推!只到剩下一个人为止!ACMer丹丹想知道那些位置的人依次退出!ACMer抛抛想知道最后是一个人是那个位置!做为聪明的ACMer请设计一个程序告诉她们吧!(位置编号从1开始顺时针到n)用循环链表写

 

Input

输入二个数 n 和 m。(n <= 10000 m <= 10^9)

 

Output

输出依次退出的位置编号!每个一行!以及最后一个留下的人的位置编号!

 

Sample Input

1 2 5 3

Sample Output

1 3 1 5 2 4View Code
 
#include <stdio.h>
#include <malloc.h>
typedef struct node
{
    long data;
    struct node *next;
}slnode;
void listinitiate(slnode **head)
{
    *head=(slnode *)malloc(sizeof(slnode));
    (*head)->next=*head;
    (*head)->data=1;
}

void listdelete(slnode *head,int i,long *x)
{
    slnode *p,*q;
    int j;
    p=head;
    j=-1;
    while (p->next!=head && p->next->next!=head && j<i-1)
    {
        p=p->next;
        j++;
    }
    q=p->next;
    *x=q->data;
    p->next=p->next->next;
    free(q);
}
void listget(slnode *head,int i,long *x)
{
    slnode *p;
    int j;
    p=head;
    j=-1;
    while (p->next!=head && j<i)
    {
        p=p->next;
        j++;
    }
    *x=p->data;
}
void destroy(slnode **head)
{
    slnode *p,*q;
    p=*head;
    while (p!=NULL)
    {
        q=p;
        p=p->next;
        free(q);
    }
    *head=NULL;
}
void listinsert(slnode *head,int i,long x)
{
    slnode *p,*q;
    int j;
    p=head;
    j=-1;
    while (p->next!=head && j<i-1)
    {
        p=p->next;
        j++;
    }
    q=(slnode *)malloc(sizeof(slnode));
    q->data=x;
    q->next=p->next;
    p->next=q;
}
int main()
{
    slnode *l;
    long i,x,n,m,t,a;
    while (~scanf("%d%d",&n,&m))
    {
        if (m==1
        {
            for (i=1;i<=n;i++)
                printf("%d\n",i);
            continue;
        }
        listinitiate(&l);
        for (i=0;i<n-1;i++)
        listinsert(l,i,i+2);
        a=1;
        while (n>0)
        {
            t=(m-a-1)%n;
            while (t--)
            l=l->next;
            n--;
            listdelete(l,0,&x);
            printf("%ld\n",x);
            a=0;
        }
    }    //destroy(&l);
    return 0;
posted on 2013-03-08 21:06  Modiz  阅读(97)  评论(0)    收藏  举报