公式

E - Avoid Knight Attack 解説 by en_translator


The number of available squares can be up to \(10 ^ {18}-3\), which is enormous, while the number of the unavailable ones is no greater than \(9M\), which can be entirely maintained. By managing the unavailable squares in a data structure like a hash set to deduplicate, the sought count can be found. The time complexity is about \(O(M)\) or \(O(M\log M)\).

The following is sample code.

#include <iostream>
#include <set>
#include <vector>

int main() {
    using namespace std;
    int N, M;
    cin >> N >> M;

    // The set of unavailable squares
    set<pair<int, int>> bad_cell;
    // A piece can move in these directions
    vector<pair<int, int>> knight_move{{2, 1}, {1, 2}, {-1, 2}, {-2, 1}, {-2, -1}, {-1, -2}, {1, -2}, {2, -1}};
    for (int i = 0; i < M; ++i) {
        int x, y;
        cin >> x >> y;
        bad_cell.emplace(x, y);
        for (const auto& [dx, dy] : knight_move)
            // If the destination exists
            if (1 <= x + dx && x + dx <= N && 1 <= y + dy && y + dy <= N)
                bad_cell.emplace(x + dx, y + dy);
    }

    // The answer is the number of entire cells subtracted by that of the unavailable cells.
    cout << static_cast<long>(N) * N - size(bad_cell) << endl;

    return 0;
}

投稿日時:
最終更新: