题目:
n(n<20)个人站成一圈,逆时针编号为1~n。有两个官员,A从1开始逆时针数,B从n开始顺时针数。在每一轮中,官员A数k个就停下来,官员B数m个就停下来(注意有可能两个官员停在同一个人上)。接下来被官员选中的人(1个或者2个)离开队伍。
输入n,k,m输出每轮里被选中的人的编号(如果有两个人,先输出被A选中的)。例如,n=10,k=4,m=3,输出为4 8, 9 5, 3 1, 2 6, 10, 7。注意:输出的每个数应当恰好占3列。
输入:
10 4 3
输出:
_ _ 4_ _ 8,_ _ 9_ _ 5,_ _ 3_ _ 1,_ _ 2_ _ 6,_ 10,_ _ 7
#include <stdio.h>
#define maxn 25
int a[maxn];
int n,k,m;
int run(int p, int d, int t)
{
while(t--)
{
do
{
p = (p + d + n - 1) % n + 1; //这里理解的还不是很到位。。。。好心人,解释一下,这是怎么做到的
}while(a[p] ==0); //走到下一个非0数字
}
return p;
}
int main()
{
while(scanf("%d%d%d",&n,&k,&m) == 3 && n)
{
int i;
for(i = 1; i <= n; i++)
{
a[i] = i;
}
int left = n;
int p1 = n, p2 = 1;
while(left)
{
p1 = run(p1,1,k);
p2 = run(p2,-1,m);
printf("%3d",p1);
left--;
a[p1] = 0;
if(p1 != p2)
{
printf("%3d",p2);
left--;
a[p2] = 0;
}
if(left)
{
printf(",");
}
}
printf("\n");
}
return 0;
}
平时自己写代码一般都不会用do while循环,这个例子很好的利用了它的好处
do while至少会执行一次,表达式为真会继续循环
do-while语句的一般形式为:
do
语句
while(表达式);
这个循环与while循环的不同在于:它先执行循环中的语句,然后再判断表达式是否为真,如果为真则继续循环;如果为假,则终止循环。因此,do-while循环至少要执行一次循环语句。其执行过程可用下图表示。