武汉科技大学ACM:1001: 猴子选大王
Problem Description
n只猴子要选大王,选举方法如下:所有猴子按 1,2 ……… n 编号并按照顺序围成一圈,从第 k 个猴子起,由1开始报数,报到m时,该猴子就跳出圈外,下一只猴子再次由1开始报数,如此循环,直到圈内剩下一只猴子时,这只猴子就是大王。
Input
猴子总数n,起始报数的猴子编号k,出局数字m。(2=<n<=20,k<=n)
Output
猴子的出队序列(不包括猴子大王)和猴子大王的编号。
Sample Input
6 5 9 3 3 11
Sample Output
1 5 6 4 2 3 1 2 3
HINT
1 #include <stdio.h> 2 #include <stdlib.h> 3 typedef struct node 4 { 5 int data; 6 struct node *next; 7 }linklist; 8 9 int main() 10 { 11 int i, n, k, m, total; 12 linklist *head, *p, *s, *q; 13 while(scanf("%d%d%d",&n,&k,&m)!=EOF) 14 { 15 head = (linklist*) malloc(sizeof(linklist)); 16 p = head; 17 p->data = 1; 18 p->next = p; 19 for (i = 2; i <= n; i++) 20 { 21 s = (linklist*) malloc(sizeof(linklist)); 22 s->data = i; 23 s->next = p->next; 24 p->next = s; 25 p = p->next; 26 } 27 p = head; 28 for (i = 1; i < k; i++) 29 { 30 p = p->next; 31 } 32 total = n; 33 q = head; 34 while (total != 1) 35 { 36 for (i = 1; i < m; i++) 37 { 38 p = p->next; 39 } 40 if(total>2) 41 printf("%d ", p->data); 42 else 43 printf("%d", p->data); 44 while (q->next != p) 45 { 46 q = q->next; 47 } 48 q->next = p->next; 49 s = p; 50 p = p->next; 51 free(s); 52 total--; 53 } 54 printf("\n%d\n", p->data); 55 free(p); 56 } 57 return 0; 58 }