Loading

E. Counting Rectangles(思维 二维前缀和) CF 1722E

题目:

​ 给出一个长度为\(1e5\)的矩阵序列和\(1e5\)次询问,每次询问给出两个上下界矩阵,保证大矩阵包含小矩阵,请输出矩阵序列中所有能包含小矩阵且被大矩阵包含的矩阵面积和。矩阵不能被旋转。

包含:A包含B,当且仅当A的长宽都大于B,或者A的长等于B,宽大于B,或者A的宽等于B,长大于B。

分析:

​ 由于拥有\(1e5\)次数的查询,所以我们可以简单的想到用前缀和来维护面积和,且可以发现题目询问的包含关系是满足单调的。所以我们要知道的就是,如何快速找到这个包含关系。用公式表示这个包含关系就是\({h1 \le h \le h2,w1 \le w \le w2}(h和w不能同时等于下界或上界)\)。将问题抽象化,可以用\(a[x][y]\)表示长为x,宽为y的矩阵的面积,那么通过二维前缀和就可以\(O(1)\)查询包含小矩阵且被大矩阵包含的所有矩阵的面积和。

实现:

​ 抽象之后就是二维前缀和模板题,记得初始化数组。

#include <bits/stdc++.h>
    
using namespace std;
#define rep(i, a, n) for(int i = a; i < n; i++)
#define all(x) x.begin(), x.end()
#define pb push_back
#define ios ios::sync_with_stdio(false);cin.tie(0);
#define debug(x)    cout << x << endl;
#define SZ(x)    (int)x.size()
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int, int> PII;
const int inf = 0x3f3f3f3f;
void read(int &x) {int s = 0, f = 1; char ch = getchar(); while(!isdigit(ch)) {f = (ch == '-' ? -1 : f); ch = getchar();} while(isdigit(ch)) {s = s * 10 + ch - '0'; ch = getchar();} x = s * f;}

const int N = 1005;
int n, m;
LL a[N][N], s[N][N];

void init()
{
    memset(a, 0, sizeof a);
}

void solve()
{
    init();
    cin >> n >> m;
    rep(i, 0, n)
    {
        LL h, w; cin >> h >> w;
        a[h][w] += h * w;
    }

    rep(i, 1, N)
    rep(j, 1, N)
        s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1] + a[i][j];

    while(m --)
    {
        LL h1, w1, h2, w2;
        cin >> h2 >> w2 >> h1 >> w1;
        cout << s[h2][w2] + s[h1 - 1][w1 - 1] - s[h2][w1 - 1] - s[h1 - 1][w2] << '\n';
    }
}

signed main()
{
    ios;
    int _ = 1;
    cin >> _;
    while(_--)
        solve();
}
posted @ 2022-09-01 11:15  DM11  阅读(141)  评论(0编辑  收藏  举报