uva133

In a serious attempt to downsize (reduce) the dole queue, The New National Green Labour Rhinoceros Party has decided on the following strategy. Every day all dole applicants will be placed in a large circle, facing inwards. Someone is arbitrarily chosen as number 1, and the rest are numbered counter-clockwise up to N (who will be standing on 1's left). Starting from 1 and moving counter-clockwise, one labour official counts off k applicants, while another official starts from N and moves clockwise, counting m applicants. The two who are chosen are then sent off for retraining; if both officials pick the same person she (he) is sent off to become a politician. Each official then starts counting again at the next available person and the process continues until no-one is left. Note that the two victims (sorry, trainees) leave the ring simultaneously, so it is possible for one official to count a person already selected by the other official.

Input

Write a program that will successively read in (in that order) the three numbers (N, k and m; k, m > 0, 0 < N < 20) and determine the order in which the applicants are sent off for retraining. Each set of three numbers will be on a separate line and the end of data will be signalled by three zeroes (0 0 0).

Output

For each triplet, output a single line of numbers specifying the order in which people are chosen. Each number should be in a field of 3 characters. For pairs of numbers list the person chosen by the counter-clockwise official first. Separate successive pairs (or singletons) by commas (but there should not be a trailing comma).

Sample input

10 4 3
0 0 0

Sample output

 4  8,  9  5,  3  1,  2  6,  10,  7

where  represents a space.



思路:

本来想用list做的。。可是错以为是循环链表了 尾巴可以指向头。。

看了别人写的代码。。

假设当前位置为current(取值从0-N-1) 顺时针数K个时候可能的越界就是current+k可能会大于N-1,此时我们一步一步的算。。 当current+1>N-1的时候表示current+1=N 已经越界 此时current应该等于0, 而(current+1)%N 正好等于0.

当逆时针数M个的时候可能的越界就是current-1<0,则current-1=-1;此时current应当等于N-1,而current-1+N=N-1,所以(current-1+N)%N就等于N-1;  

而(current+1+N)%N=(current+1)%N 那么顺时针和逆时针就可以共用一个公式(current+N+index(标志))%N。此时Index为顺时针逆时针的标志 顺时针为1 逆时针为-1.


代码如下:

#include<iostream>
using namespace std;
int index[20];
int N, k, m;
int modify(int cur,int judge,int step)
{
while (step--)//一步一步走 判断是否越界
{
cur = (cur + judge + N) % N; //当前位置cur(0,N-1)  cur+1>N-1 cur+1=N  cur-1<0 cur-1=-1
if (index[cur] == 0)
step++;
}
return cur;
}
int main()
{
int i=0;
int total;
while (cin >> N >> k >> m && N + k + m)
{
for (i = 0; i < N; i++)
index[i] = i + 1;


total = N;
int a = 0, b = N - 1;
while (total)
{
a = modify(a, -1, m);
b = modify(b, 1, k);
printf("%3d", b + 1);
index[b] = 0;
total--;
if (a != b){
printf("%3d", a + 1); total--; index[a] = 0;
}
if (total) printf(",");
}
printf("\n");
}
return 0;
}

你可能感兴趣的:(uva133)