洛谷P1518 [USACO2.4] 两只塔姆沃斯牛 The Tamworth Two 题解

洛谷P1518 [USACO2.4] 两只塔姆沃斯牛 The Tamworth Two 题解

题目传送门

思路

使用简单的模拟思想来模拟Farmer John和2头牛的移动过程,唯一的难点在于如何判断是否永远无法抓到2头牛。

这个难点可以使用一个简单的六维bool型数组来判断,若在某一时间点,2个移动对象的坐标以及方向都与之前的另一时间点相同,则代表他们陷入了死循环,自然就永远无法抓到对方了。

代码

#include<bits/stdc++.h>
#define endl '\n'

using namespace std;

const int INF = 0x3f3f3f3f;
const double EPS = 1e-8;
const int N = 15;

int cx, cy, cd, jx, jy, jd;
int fx[4] = { -1, 0, 1, 0};
int fy[4] = {0, 1, 0, -1};
char mp[N][N];
bool vis[N][N][N][N][5][5];

void movecows() {
	int tx = cx + fx[cd];
	int ty = cy + fy[cd];
	if(tx >= 1 && tx <= 10 && ty >= 1 && ty <= 10 && mp[tx][ty] != '*') {
		cx = tx;
		cy = ty;
	} else {
		cd++;
		cd %= 4;
	}
}

void movejohn() {
	int tx = jx + fx[jd];
	int ty = jy + fy[jd];
	if(tx >= 1 && tx <= 10 && ty >= 1 && ty <= 10 && mp[tx][ty] != '*') {
		jx = tx;
		jy = ty;
	} else {
		jd++;
		jd %= 4;
	}
}

int main() {
	for(int i = 1; i <= 10; i++) {
		for(int j = 1; j <= 10; j++) {
			cin >> mp[i][j];
			if(mp[i][j] == 'F') {
				mp[i][j] = '.';
				jx = i;
				jy = j;
			} else if(mp[i][j] == 'C') {
				mp[i][j] = '.';
				cx = i;
				cy = j;
			}
		}
	}
	int minu = 0;
	while(1) {
		if(vis[cx][cy][jx][jy][cd][jd]) {
			cout << 0 << endl;
			break;
		}
		vis[cx][cy][jx][jy][cd][jd] = 1;
		minu++;
		movecows();
		movejohn();
		if(cx == jx && cy == jy) {
			cout << minu << endl;
			break;
		}
	}
	return 0;
}

AC记录

AC记录,28ms,648.00KB

posted @ 2025-02-17 13:39  2789617221guo  阅读(77)  评论(0)    收藏  举报