joseplus问题
问题重述:设有n个人围坐在一个圆桌周围,现从第s个人开始报数,数到第m的人出列,然后从出列的下一个人重新开始报数,数到第m的人又出列……求出列次序。
思路:用数组存储,数组长度为n+1.第0个不用。每数到一个人,将它的值移动到最后,然后将这个人之后的没有出列的人向前移动一位。直到只剩下一个人。
1 #include <stdio.h>
2 #include <malloc.h>
3
4 int main(int argc, char **argv)
5 {
6 int n, m, s; // n: the whole people
7 // m: the length to select a people
8 // s: begin from
9 int s1; // s1:current point people
10 int *p; // p: point to array
11 int i, j;
12 int tmp;
13 printf("Input n, m and s:\n");
14 scanf("%d %d %d", &n, &m, &s);
15 p = (int *)malloc((n + 1) * sizeof(int));
16
17 //init
18 s1 = s;
19 for (i = 1;i <= n; i++){
20 p[i] = i;
21 }
22
23 for (i = n; i >= 1; i--){
24 s1 = (s1 + m - 1) % i;
25 if (0 == s1){
26 s1 = i;
27 }
28 tmp = p[s1];
29 for (j = s1; j <= i - 1; j++ ){
30 p[j] = p[j+1];
31 }
32 p[i] = tmp;
33 }
34
35 for (i = 1; i <= n / 2; i++){
36 tmp = p[i];
37 p[i] = p[n-i+1];
38 p[n-i+1] = tmp;
39 }
40
41 //print the result
42 printf("The people order is:\n");
43 for(i = 1;i <= n;i++){
44 printf("%d\t",p[i]);
45 }
46 printf("\n");
47
48 return 0;
49 }
posted on 2013-06-03 00:51 telnetning 阅读(227) 评论(0) 编辑 收藏 举报