九度OJ 1189:还是约瑟夫环 (约瑟夫环)

时间限制:1 秒

内存限制:32 兆

特殊判题:

提交:820

解决:522

题目描述:

生成一个长度为21的数组,依次存入1到21;
建立一个长度为21的单向链表,将上述数组中的数字依次存入链表每个结点中;
将上述链表变为单向封闭(循环)链表;从头结点开始数,将第17个结点删除,将它的下一个结点作为新的头结点;
重复上述过程,直到该链表中只剩一个结点,显示该结点中存入的数字。

输入:

没有任何输入数据。

输出:

输出上面题目描述中最后剩下的节点中存入的数字。

样例输入:

样例输出:

提示:

请不要直接输出数据水过去,这样达不到提升自己的目的,
请按照题目要求来做题,这样到真正考试时才能应对自如。

来源:
2003-2005年华中科技大学计算机研究生机试真题

思路:

这是约瑟夫环更简单的情形。


代码:

#include <stdio.h>
#include <string.h>
 
#define N 21
 
int n, p, cur, cur0;
int next[N+1];
 
void init()
{
    n = 21;
    p = 17;
    for (int i=1; i<n; i++)
        next[i] = i+1;
    next[n] = 1;
    cur0 = n;
    cur = 1;
}
 
int main(void)
{
    int i;
 
    init();
    while (n > 1)
    {
        for (i=1; i<(p%n==0 ? n : p%n); i++)
        {
            cur0 = cur;
            cur = next[cur];
        }
        n --;
        //printf("%d ", cur);
        cur = next[cur];
        next[cur0] = cur;
    }
    printf("%d\n", cur);
 
    return 0;
}
/**************************************************************
    Problem: 1189
    User: liangrx06
    Language: C
    Result: Accepted
    Time:0 ms
    Memory:908 kb
****************************************************************/


posted on 2015-10-26 11:22  梁山伯  阅读(325)  评论(0编辑  收藏  举报

导航