20180606模拟赛T1——猫鼠游戏

猫鼠游戏

(catch.pas/cpp/c)

题目描述:

猫和老鼠在10*10的方格中运动,例如:

*...*.....
......*...
...*...*..
..........
...*.C....
*.....*...
...*......
..M......*
...*.*....
.*.*......

C = 猫(CAT) M = 老鼠(MOUSE) * = 障碍物 . = 空地

猫和老鼠每秒中走一格,如果在某一秒末他们在同一格中,我们称他们“相遇”。

注意,“对穿”是不算相遇的。猫和老鼠的移动方式相同:平时沿直线走,下一步如果会走到障碍物上去或者出界,就用1秒的时间做一个右转90度。一开始他们都面向北方。 编程计算多少秒以后他们相遇。

输入文件

10行,格式如上。

输出文件

相遇时间T。如果无解,输出-1。

样例输入

*...*.....
......*...
...*...*..
..........
...*.C....
*.....*...
...*......
..M......*
...*.*....
.*.*......

样例输出

49

题解

正解应该就是暴力模拟吧……对于普通解法就直接贴代码吧

#include <cstdlib>
#include <cstdio>
#include <iostream>

using namespace std;

const int maxn = 10;

int mx, my;
int cx, cy;
int cd, md;

char mmap[maxn][maxn];

int dirx[] = {-1, 0, 1, 0};
int diry[] = {0, 1, 0, -1};

int main()
{
    freopen("catch.in", "r", stdin);
    freopen("catch.out", "w", stdout);
    for(int i = 1; i <= 10; ++i)
    {
        gets(mmap[i]+1);
        for(int j = 1; j <= 10; ++j)
        {
            if(mmap[i][j] == 'C')
            {
                cx = i;
                cy = j;
            }
            else if(mmap[i][j] == 'M')
            {
                mx = i;
                my = j;
            }
        }
    }
    cd = md = 0;
    for(int bs = 1; bs <= 10000; ++bs)//如果步数大于10000就跳掉,这里不能保证正确性
    {
        int tx = mx + dirx[md];
        int ty = my + diry[md];
        if(mmap[tx][ty] == '*' || !tx || tx > 10 || !ty || ty > 10)
            md = (md+1) % 4;//右转
        else
        {
            mx = tx;
            my = ty;
        }
        tx = cx + dirx[cd];
        ty = cy + diry[cd];
        if(mmap[tx][ty] == '*' || !tx || tx > 10 || !ty || ty > 10)
            cd = (cd+1) % 4;
        else
        {
            cx = tx;
            cy = ty;
        }
        if(mx == cx && my == cy)
        {
            printf("%d", bs);
            return 0;
        }
    }
    puts("-1");
    return 0;
}

是否感觉bs <= 10000太草率了?于是我们可以考虑找到环后直接用exgcd解方程,

猜你喜欢

转载自www.cnblogs.com/pfypfy/p/9146528.html