代码

· · 个人记录

/*
 * _|_|_|_|  _|_|_|    _|_|_|  _|_|_|_|  _|_|    _|_|
 *     _|    _|    _|  _|    _|    _|  _|    _|  _|
 *   _|    _|_|_|    _|_|_|  _|_|_|_|  _|    _|  _|_|
 * _|    _|    _|  _|    _|  _|    _|  _|_|_|_|  _|_|_|
 */

#include <bits/stdc++.h>

int main() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);

    int N, M;
    std::cin >> N >> M;
    std::vector<std::string> mp(N);
    for (auto &v: mp) { std::cin >> v; }

    long long ans = 0;
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < M; j++) {
            if (mp[i][j] == '1') {
                if (j == M - 1 || mp[i][j + 1] != '1') {
                    ans += 1LL * (i + 1) * (N - i);
                }
                if (i != N - 1 && mp[i + 1][j] == '1') {
                    ans -= 1LL * (i + 1) * (N - i - 1);
                }
            }
        }
    }

    std::vector<std::vector<bool>> vis(N, std::vector<bool>(M));
    for (int i = 1; i < N; i++) {
        for (int j = 1; j < M; j++) {
            if (vis[i][j]) { continue; }
            int U = i, D = i, L = j, R = j;
            std::queue<std::pair<int, int>> que;
            que.emplace(i, j);
            while (!que.empty()) {
                int x, y;
                std::tie(x, y) = que.front(), que.pop();
                U = std::min(U, x), D = std::max(D, x);
                L = std::min(L, y), R = std::max(R, y);
                if (x <= 0 || y <= 0 || x >= N || y >= M || vis[x][y]) { continue; }
                vis[x][y] = true;
                if (mp[x][y] != '1' || mp[x - 1][y] != '1') { que.emplace(x, y + 1); }
                if (mp[x][y] != '1' || mp[x][y - 1] != '1') { que.emplace(x + 1, y); }
                if (mp[x][y - 1] != '1' || mp[x - 1][y - 1] != '1') {
                    que.emplace(x, y - 1);
                }
                if (mp[x - 1][y] != '1' || mp[x - 1][y - 1] != '1') {
                    que.emplace(x - 1, y);
                }
            }
            if (L != 0 && R != M) { ans += 1LL * U * (N - D); }
        }
    }

    std::cout << ans << '\n';

    return 0;
}