刘佳汝书上的例题,82页4-3,没什么难度,他说的很详细了,我稍微注释了一下。
#include#define maxn 25int n, k, m, a[maxn];int go(int p, int d, int t)//用d的+-1取值来代表向前走和向后走{ while (t--) { do { p = (p + d + n - 1) % n + 1; } while (a[p] == 0);//走到下一个非零数字其中-1是为了平衡d为+1的情况,最后+1是为了平衡d为-1的情况 } return p;}int main(){ 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;}
下边的今天自己写的,说实话他那个卡范围的表达式是真的难想,退而求其次了。
还有,%3d可真好用!
#include#include using namespace std;int Q[25];int k, m, n;int go(int t, int x, int i){ while (x--) { do { t += i; if (t <= 0) t = n; if (t >= n + 1)t = 1; } while (!Q[t]); } return t;}int main(){ cin.tie(0); cin.sync_with_stdio(false); //memset(Q, 0, sizeof(Q)); while (cin >> n >> k >> m) { if (!(k || m || n)) { break; } int _cnt = n; //初始化队列 for (int i = 0; i <= n; i++) { Q[i] = i; } //发放救济金 int a = 0, b = 0; while (_cnt) { a = go(a, k, 1); b = go(b, m, -1); if (a == b) { Q[a] = 0; cout << setiosflags(ios::fixed) << setiosflags(ios::right); cout << setw(3) << a;//格式化输出 _cnt--; } else { Q[a] = 0; Q[b] = 0; cout << setw(3) << a << setw(3) << b; _cnt -= 2; } if(_cnt!=0) cout<< ","; } cout << endl; } return 0;}