报数问题
共有n个人,每次淘汰报数为m的人,直至队伍剩一人,输出最后剩余的人初始编号
#include <iostream>
#include <queue>
using namespace std;
int main()
{
int n,m;
cin>>n>>m;
queue<int> q;
for(int i=1;i<=n;i++)
{
q.push(i);
}
int cur=1;//记录当前报数
while(q.size()>1)
{
int t=q.front();
q.pop();
cout<<t<<endl;
if(cur==m)
{
cur=1;
}
else
{
q.push(t);
cur++;
}
}
cout<<q.front();
return 0;
}
迷宫游戏
#include <iostream>
#include <queue>
using namespace std;
int n,m;
bool visit[100][100];
int dir[4][2]={{-1,0},{1,0},{0,-1},{0,1}};
char mat[100][100];
struct node
{
int x,y,d;
node(int xx,int yy,int dd)
{
x=xx;
y=yy;
d=dd;
}
};
int in(int x,int y)
{
return x<n&&x>=0&&y<m&&y>=0;
}
int bfs(int sx,int sy)
{
queue<node> q;
int tx,ty;
q.push(node(sx,sy,0));
visit[sx][sy]=true;
while(!q.empty())
{
node n=q.front();
q.pop();
for(int i=0;i<4;i++)
{
tx=n.x+dir[i][0];
ty=n.y+dir[i][1];
//q.push(node(tx,ty,n.d+1));
if(in(tx,ty)&&mat[tx][ty]!='*'&&!visit[tx][ty])
{
if(mat[tx][ty]=='T')
return n.d+1;
else
{
visit[tx][ty]=true;
q.push(node(tx,ty,n.d+1));
}
}
}
}
return 0;
}
int main()
{
cin>>n>>m;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
cin>>mat[i][j];
}
}
int x,y;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(mat[i][j]=='S')
{
x=i;
y=j;
}
}
}
cout<<bfs(x,y);
return 0;
}
在一个长度为 n 的坐标轴上,蒜头君想从 A 点 移动到 B 点。他的移动规则如下:
向前一步,坐标增加 1。
向后一步,坐标减少 1。
跳跃一步,使得坐标乘 2。
蒜头君不能移动到坐标小于 0 或大于 n 的位置。蒜头想知道从 A 点移动到 B 点的最少步数是多少,你能帮他计算出来么?
#include <iostream>
#include <queue>
using namespace std;
int n,a,b;
bool visit[100];
struct node
{
int x,step;
node(int xx,int s)
{
x=xx;
step=s;
}
};
int bfs(int a)
{
queue<node> q;
q.push(node(a,0));
visit[a]=true;
while(!q.empty())
{
node now=q.front();
q.pop();
if(now.x==b)
return now.step;
if(now.x+1<=n)
{
visit[now.x+1]=true;
q.push(node(now.x+1,now.step+1));
}
if(now.x-1>=0)
{
visit[now.x-1]=true;
q.push(node(now.x-1,now.step+1));
}
if(now.x*2<=n)
{
visit[now.x*2]=true;
q.push(node(now.x*2,now.step+1));
}
}
return 0;
}
int main()
{
cin>>n>>a>>b;
cout<<bfs(a)<<endl;;
return 0;
}