题目链接:圆桌问题
题目:
圆桌上围坐着2n个人。其中n个人是好人,另外n个人是坏人。如果从第一个人开始数数,数到第m个人,则立即处死该人;然后从被处死的人之后开始数数,再将数到的第m个人处死……依此方法不断处死围坐在圆桌上的人。试问预先应如何安排这些好人与坏人的座位,能使得在处死n个人之后,圆桌上围坐的剩余的n个人全是好人。
Input
多组数据,每组数据输入:好人和坏人的人数n(<=32767)、步长m(<=32767);
Output
对于每一组数据,输出2n个大写字母,‘G’表示好人,‘B’表示坏人,50个字母为一行,不允许出现空白字符。相邻数据间留有一空行。
Sample Input 1
2 3
Sample Input 2
2 4
Sample Output 1
GBBG
Sample Output 2
BGGB
思路:以前用的循环来判断位置,因为每次都有人要离开,直接用取模是不可行的,这次用vector模拟圆环,走一个删一个,但是要注意取 模边界和删除走的人为最后一个时下一个人的坐标的改变
代码:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<vector>
using namespace std;
char vis[66666];
vectorp;
int n,m,N;
int pos;
int flag=0;
int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
p.clear();
memset(vis,'G',sizeof(vis));
N=2*n;
pos=1;
for(int i=1;i<=N;i++)
p.push_back(i);
while(N>n)
{
pos=pos+m-1;
if(pos>N)
{
pos%=N;
if(pos==0)
pos=N;
}
vis[p[pos-1]]='B';
p.erase(p.begin()+pos-1);
if(pos==N)
pos=1;
N--;
}
N=2*n;
for(int i=1;i<=N;i++)
{
printf("%c",vis[i]);
if(i%50==0)
printf("\n");
}
printf("\n\n");
}
return 0;
}
网友评论