圆桌问题
问题描述 :
圆桌上围坐着2n个人。其中n个人是好人,另外n个人是坏人。如果从第一个人开始数数,数到第m个人,则立即处死该人;然后从被处死的人之后开始数数,再将数到的第m个人处死……依此方法不断处死围坐在圆桌上的人。试问预先应如何安排这些好人与坏人的座位,能使得在处死n个人之后,圆桌上围坐的剩余的n个人全是好人。
输入说明 :
输入:好人和坏人的人数n(<=32767)、步长m(<=50);
输出说明 :
输出2n个大写字母,‘G’表示好人,‘B’表示坏人,50个字母为一行。
输入范例 :
52 6
输出范例 :
BGGBGBGGBBBBGGGGBBBGBGGBGBBGGBBGBGBBGGGBBBGBGGBBGG
BBGBBGGGGBBBBGGBGGBBGBBGGBGBBGGBBBGGBGGBBGGGBBGBGG
GBGB
#include <stdio.h> #include <stdlib.h> #include <iostream> #include <vector> using namespace std; typedef struct people { char ch; struct people* next; people(char c):ch(c){} }People; void my_print(People* head) { People* p = head; int count = 0; while (p->next != head) { if (count && count % 50 == 0)cout << endl; cout << p->ch; count++; p = p->next; } cout << p->ch; //cout << endl << endl; } void my_fun(People* head, int n, int m) { int i, count = m; People* p = head; for (i = 0; i < n; i++) { while (1) { if (p->ch == 'G') { count--; if (!count)break; } p = p->next; } p->ch = 'B'; //my_print(head); count = m; } } int main() { int n, m; scanf("%d%d", &n, &m); vector<People*> people_vec; int i; for (i = 0; i < 2*n; i++) people_vec.push_back(new People('G')); for (i = 0; i < 2 * n - 1; i++) people_vec[i]->next = people_vec[i + 1]; people_vec[2*n-1]->next = people_vec[0]; People* head = people_vec[0]; my_fun(head,n,m); my_print(head); return 0; }