您的位置:首页 > 其它

Codeforces Round #416 (Div. 2) D. Vladik and Favorite Game 交互, BFS

2017-06-28 21:26 405 查看

题目链接: Vladik and Favorite Game

题目大意

一幅n*m地图,
.
代表可以走的位置,
*
代表不可以走的位置,
F
代表终点, 一开始人在(1, 1)位置, 有四个按钮
U D L R
, 代表上下左右移动, 输出方向后, 人会移动, 然后交互器会给出移动后的位置

其中
U
D
的功能可能会被交换,
L
R
的功能也可能会被交换(从一开始就被交换了或没有被交换, 之后整个游戏都不变), 如果在边界向边界方向移动, 移动后的位置不变, 如果你移动后的位置是
*
游戏失败

要在n*m的步数内走到终点

思路

首先要判断出那些按钮功能被交换了, 同时还有保证不会走到有
*
的位置

一开始的位置是(1, 1), 如果右边的位置不是
*
, 那就往右走试一下(
R
), 如果位置不变, 就说明
L
R
功能交换了, 同理判断出另一对按钮的情况

然后BFS记录路径, 输出到终点的答案

代码

#include <bits/stdc++.h>
using namespace std;

const int MAXN = 110, inf = 0x3f3f3f3f;
char mp[MAXN][MAXN];
int n, m, x, y, last[MAXN][MAXN];
char button[4] = {'U', 'D', 'L', 'R', };
void Move(int i)
{
printf("%c\n", button[i]);
cout.flush();
scanf("%d%d", &x, &y);
--x; --y;
}
#define move(i) {Move(i); if(mp[x][y] == 'F') return 0; }//移动并判断是否到达F, 到达了就直接结束程序
typedef pair<int, int> P;

int main()
{
scanf("%d%d", &n, &m);
for(int i=0; i<n; ++i) scanf("%s", mp[i]);
if(mp[0][1] != '*' && mp[1][0] != '*')//起点右方下方都可以走
{
move(1);
if(x==0 && y==0) swap(button[0], button[1]);//位置没变, 说明按钮被交换
else move(0);
move(3);
if(x==0 && y==0) swap(button[2], button[3]);
else move(2);
}
else if(mp[0][1] != '*')//起点右方可以走, 下方不可以走
{
move(3);
if(x==0 && y==0) swap(button[2], button[3]);
else move(2);

while(mp[x+1][y] == '*') move(3);//走到一个可以往下走的位置以判断另一对按钮的情况, 不用担心走到'*', 因为要么直接就遇到F了, 要么肯定有一个位置可以往下走
move(1);
if(x==0) swap(button[0], button[1]);
}
else//同上
{
move(1);
if(x==0 && y==0) swap(button[0], button[1]);
else move(0);

while(mp[x][y+1] == '*') move(1);
move(3);
if(y==0) swap(button[2], button[3]);
}
//bfs记录路径
memset(last, -1, sizeof(last));
int x0 = x, y0 = y;
queue<P> que;
que.push(P(x0, y0));
int dx[] = {-1, 1, 0, 0, };
int dy[] = {0, 0, -1, 1, };
int fx, fy;
while(!que.empty())
{
P p = que.front(); que.pop();
if(mp[p.first][p.second] == 'F')
{
fx = p.first;
fy = p.second;
break;
}

for(int i=0; i<4; ++i)
{
int nx = p.first + dx[i], ny = p.second + dy[i];
if(0<=nx && nx<n && 0<=ny && ny<m && mp[nx][ny]!='*' && last[nx][ny] == -1)
{
que.push(P(nx, ny));
last[nx][ny] = i;
}
}
}

vector<int> path;
auto f = [&](int i) {fx += dx[i]; fy += dy[i]; };
while(true)
{
if(fx==x0 && fy==y0) break;
if(last[fx][fy] == 0) path.push_back(0), f(1);
else if(last[fx][fy] == 1) path.push_back(1), f(0);
else if(last[fx][fy] == 2) path.push_back(2), f(3);
else if(last[fx][fy] == 3) path.push_back(3), f(2);
}
for(int i=int(path.size()-1); i>=0; --i) move(path[i]);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: