跳到正文

题解

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

EnjoySilence约 3 分钟
原文
文章信息与版本

文章信息

发布
2025年7月21日
收录
2026年9月23日
更新
2026年11月11日
篇幅
约 3 分钟
获赞
18
题目
P1518

版本

  1. v1当前

更好的阅读体验。

思路

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

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

代码

C++
#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。

原文
存档评论9 条抓取于