算法刷题记录:P1518 [USACO2.4]两只塔姆沃斯牛 The Tamworth Two
题目链接:
https://www.luogu.com.cn/problem/P1518
题目分析
这道模拟题很典型了,给定了一个固定的移动方式,去模拟即可,
该题说:如果牛和农夫永远不会相遇输出0,我没想到很好的方法,不推荐我这样的写法。
算勉强AC吧。
AC代码
// Problem: P1518 [USACO2.4]两只塔姆沃斯牛 The Tamworth Two
// Contest: Luogu
// URL: https://www.luogu.com.cn/problem/P1518
// Memory Limit: 125 MB
// Time Limit: 1000 ms
//
// Powered by CP Editor (https://cpeditor.org)
// 按照固定的运动进行模拟
#include <iostream>
int n, cnt;
char m[15][15];
int walk[4][2] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
struct ST{
int x, y, z;
};
void get_st(struct ST &F, struct ST &C)
{
int fdx = F.x + walk[F.z][0], fdy = F.y + walk[F.z][1];
int cdx = C.x + walk[C.z][0], cdy = C.y + walk[C.z][1];
// 控制农夫, 顺时针旋转
if (fdx < 1 || fdx > 10 || fdy < 1 || fdy > 10) F.z = (F.z + 1) % 4;
else if (m[fdx][fdy] == '*') F.z = (F.z + 1) % 4;
else F.x = fdx, F.y = fdy;
// 控制牛, 顺时针旋转
if (cdx < 1 || cdx > 10 || cdy < 1 || cdy > 10) C.z = (C.z + 1) % 4;
else if (m[cdx][cdy] == '*') C.z = (C.z + 1) % 4;
else C.x = cdx, C.y = cdy;
}
int main()
{
struct ST F, C;
for (int i = 1; i <= 10; ++ i)
for (int j = 1; j <= 10; ++ j){
char c; std::cin >> c;
if (c == 'F') F.x = i, F.y = j, F.z = 0;
if (c == 'C') C.x = i, C.y = j, C.z = 0;
m[i][j] = c;
}
// std::cout << F.x << ' ' << F.y << std::endl << C.x << ' ' << C.y << std::endl;
int flag = 1;
while (true){
if (F.x == C.x && F.y == C.y) break;
if (cnt >= 10000) { flag = 0; break; }
else{
++ cnt;
get_st(F, C);
}
}
if (!flag) std::cout << flag;
else std::cout << cnt;
}
本文来自博客园,作者:想个昵称好难ABCD,转载请注明原文链接:https://www.cnblogs.com/ClockParadox43/p/17471873.html