TopCoder SRM 681 Div. 2 Problem 500 - ExplodingRobots (枚举)

题意

两个机器人一开始在不同的坐标,有一个上下左右的指令序列,他们可以按顺序任意执行一些指令,问有没有可能到同一个地方。

思路

一般都会先想到记录一下两只机器人能走过的地方,如果有重复就能爆炸。

然而指令长度为50,这样需要 250 ,肯定不行。

注意到X和Y相距很小,那么我们可以枚举一只机器人理论上能活动的每一个点,看看第二只能不能到这个点。
判断的方法很简单,看看那只机器人到这个点需要几步方向即可。
然后我们一开始预处理一下每个方向的数量。

代码

class ExplodingRobots {
public:
    int num[5] = {0};
    bool can_arrive(int needx, int needy) {
        //0123 上下左右
        if (needx < 0) {
            if (num[2] < -needx) return false;
        }
        else {
            if (num[3] < needx) return false;
        }
        if (needy < 0) {
            if (num[1] < -needy) return false;
        }
        else {
            if (num[0] < needy) return false;
        }
        return true;
    }

    string canExplode(int x1, int y1, int x2, int y2, string instructions) {
        for (char cmd : instructions) {
            if (cmd == 'U') ++num[0];
            else if (cmd == 'D') ++num[1];
            else if (cmd == 'L') ++num[2];
            else ++num[3];
        }
        int left = x1 - 50, right = x1 + 50;
        int up = y1 + 50, down = y1 - 50;
        for (int x = left; x <= right; ++x) {
            for (int y = down; y <= up; ++y) {
                if (can_arrive(x - x1, y - y1) && can_arrive(x - x2, y - y2))
                    return "Explosion";
            }
        }
        return "Safe";
    }
};

你可能感兴趣的:(ICPC)