通过本题,学习到的内容有:
1.结果不是必须全部算完之后再一次输出,可以边算边输;同时这种写法也可以改善最后一个输出结果和前面的输出结果有格式误差的情况;
2.用一个变量表示1(-1),可以表示两个相反的移动方向;
****************************
问题:
在本题的go函数中,p表达式的作用是什么,可以看得出来。但是这个式子,自己恐怕是写不出的。
// UVa133 The Dole Queue
// Rujia Liu
#include<stdio.h>
#define maxn 25
int n, k, m, a[maxn];
// 逆时针走t步,步长是d(-1表示顺时针走),返回新位置
int go(int p, int d, int t) //p为起始位置
{//步长是t,即走t步
while(t--)
{
do {
p = (p+d+n-1) % n + 1;
}
while(a[p] == 0); // 走到下一个非0数字
}
return p;
}
int main()
{//n为总人数,k为逆时针步长,m为顺时针步长
while(scanf("%d%d%d", &n, &k, &m) == 3 && n)
{
for(int i = 1; i <= n; i++) a[i] = i;
int left = n; // 还剩下的人数
int p1 = n, p2 = 1;
while(left)
{
p1 = go(p1, 1, k);
p2 = go(p2, -1, m);
printf("%3d", p1); left--;//如果相等则只输出一次
if(p2 != p1) { printf("%3d", p2); left--; }
a[p1] = a[p2] = 0;
if(left) printf(",");
}
printf("\n");
}
return 0;
}