F. Bouncy Ball (模拟)

Problem - F - Codeforces

就是很普通的模拟,我们模拟这个点走的过程,如果走到一个之前走到的状态就说明陷入了循环,此时就是无解,状态可以用坐标和方向来表示,坐标 = (横坐标 - 1) * 列数 + 列坐标,方向就模拟好了,来看看手法吧,代码有注释

参考代码:

#include <bits/stdc++.h>

#define x first
#define y second
#define endl '\n'
#define int long long
#define NO {puts("NO"); return;}
#define YES {puts("YES"); return;}

using namespace std;

typedef long long ll;
typedef pair<int, int> PII;

const int mod = 1e9 + 7;
const int N = 1e6 + 10, INF = 1e18; 

int n, m;
int a[N], b[N];
string now ;
map<string, PII> dir;

int read()
{
	int x = 0, f = 1;
	char c = getchar();
	while(c < '0' || c > '9') {if(c == '-') f = -1; c = getchar();}
	while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
	return x * f;
}

bool check_n(int x)
{
	return (x >= 1 && x <= n);
}

bool check_m(int y)
{
	return (y >= 1 && y <= m);
}

void solve()
{
    int i1, j1, i2, j2;
	cin >> n >> m >> i1 >> j1 >> i2 >> j2 >> now; 
	map<int, map<string, int>> vis;
	dir["DL"] = {1, -1}, dir["DR"] = {1, 1}, dir["UR"] = {-1, 1}, dir["UL"] = {-1, -1};
	// 先定义四个方向对应的操作
	//然后我们撞墙的时候方向是相反变化的,比如上下撞墙了 D <-> U , 左右撞墙了 L <-> R 
	if(i1 == i2 && j1 == j2) {    // 先特判掉不需要走就结束的 
		cout << 0 << endl;
		return ;
	}
	int cnt = 0;
	while(1) {
		if(vis[(i1 - 1) * m + j1][now]) {     // 走进循环了 
			cout << "-1" << endl;
			return ;
		}
		vis[(i1 - 1) * m + j1][now] = 1;      // 记录一下,当前状态已经被走了 
		i1 += dir[now].x, j1 += dir[now].y;
		if(!check_n(i1) || !check_m(j1)) {    // 撞墙了 
			cnt ++ ;     
			int tmp1 = i1 - dir[now].x, tmp2 = j1 - dir[now].y;   // 记录一下撞墙之前的位置 
			if(!check_n(i1)) {     // 上下撞墙了 
				if(now[0] == 'D') now[0] = 'U';
				else now[0] = 'D';
			}
			if(!check_m(j1)){      // 左右撞墙了 
				if(now[1] == 'L') now[1] = 'R';
				else now[1] = 'L';
			}
			i1 = tmp1 + dir[now].x, j1 = tmp2 + dir[now].y;       // 把方向改正确之后,求出现在的位置 
		}
		if(i1 == i2 && j1 == j2) break;
	}
	cout << cnt << endl;
	return;
}

signed main()
{
	ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
	int t = 1;
	cin >> t;
	while(t -- ) solve();
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值