算法实验二 TEST #1

来源:互联网 发布:人民币账户黄金软件 编辑:程序博客网 时间:2024/06/05 10:29

TEST #1. (Time complexity <=O(nlogn) Hardness: Medium)

Figure 1
The Josephus problem is defined as follows: assume there are n people queuing into a circle, and there is a non-negative constant m, where m≤n. Suppose we start counting from the number 1 person in a clockwise circle and we kill the every m-th person. The process will not end till all the people are killed.
We call the sequence generated from the above process a Josephus permutation. For example, when n=7, m=3, (7,3)-Josephus permutation is <3,6,2,7,5,1,4>
Input
The input file consists of separate lines containing n,m. The last line in the input file contains 0. You can suppose that 0 < n.
Output
The output file will consist of separate lines containing the (n, m)-Josephus permutation
Sample Input
7 3
10 2
0
Sample Output
3,6,2,7,5,1,4
2,4,6,8,10,3,7,1,9,5
Hint: See your textbook on Page 190(Second Edition Chinese Version); Page 318(Second Edition English Version). You may have to realize and use the function INSERT Tree, OS-SELECT, OS-DELETE. Otherwise, you can come out with O(n) complexity algorithm.

/********************************************项目:算法实验二 TEST 1*姓名:卿***学号:SA14226**********************************************/#include "stdio.h"#include "stdlib.h"//由于order-statistic tree代码量较大// 本算法采用链表形式//节点定义struct node{    int num;    struct node *next;};/*函数名:circle_list_init输入:长度n输出:生成好的循环链表头指针功能:根据长度生成初始化的循环链表*/struct node * circle_list_init(int n){    struct node *p,*temp,*head;    int i = 0;//*******头结点生成**********    head = (struct node *)malloc(sizeof(struct node));    head->next = NULL;    head->num = 0;//*******生成链表***********    temp = head;    for(i = 1; i <= n; i++){        p = (struct node *)malloc(sizeof(struct node));        p->next = NULL;        p->num = i;        temp->next = p;        temp = p;    }    temp->next = head->next;         //构成环    return head;}/*函数名:output输入:链表head,间隔m输出:输出序列功能:输出Jonsephus permutation*/ void output(struct node * head,int m){    struct node * ptemp1, *ptemp2;    int i;    ptemp1 = head->next;    while(ptemp1->next != ptemp1)   //结束条件为只有一个节点    {        for(i = 0;i < m-1;i++){     //按照间隔移动指针            ptemp2 = ptemp1;            ptemp1 = ptemp2->next;        }        ptemp2->next = ptemp1->next;//保存该节点的后继为前一节点的后继        printf("%d,",ptemp1->num);  //输出第m位        free(ptemp1);               //删除该节点        ptemp1 = ptemp2->next;      //指针后移    }    printf("%d\n",ptemp1->num);}int main(){    int m,n;    int i;    struct node * head;    while(scanf("%d",&n)){        if(n == 0)            break;        else{            scanf("%d",&m);            head = circle_list_init(n);            output(head,m);        }    }}
0 0
原创粉丝点击