题解:AT_abc482_c [ABC482C] Band Count

· · 题解

[ABC482C] Band Count

:::info[main idea]

题目大意

给定一个 H \times W 的网格,上面有 N 个棋子,第 i 个棋子坐标为 (R_i, C_i)。

有 Q 次查询,每次为以下两种之一:

输出每次查询的棋子数。

:::success[Solutions]

做法

容易想到的暴力做法是开一个二维数组 a[i][j] 进行遍历或前缀和统计,但 1 \le H,W \le 10^9 的数据范围,显然会 MLE(甚至 TLE)。

但我们敏锐地注意到,每次查询的行和列是相互独立、互不干扰的。并且棋子的总数仅有 3 \times 10^5,这意味着我们只需要用两个一维数组分别存下所有棋子所在的行号与列号并排序。对于每次查询,通过二分查找(lower_bound 和 upper_bound)锁定区间的左右端点,相减即可得到区间内的棋子个数。

时间复杂度 O\big((N + Q) \log N\big),空间复杂度 O(N)。

:::

:::success[AC Code]

#include<bits/stdc++.h>
#define Hex return
#define AK 0
#define IOI ;
using namespace std;
const int maxn=300005;
int r[maxn],c[maxn];
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int h,w,n,q;
    cin>>h>>w>>n>>q;
    for(int i=1;i<=n;i++)
    {
        cin>>r[i]>>c[i];
    }
    sort(r+1,r+n+1);
    sort(c+1,c+n+1);
    while(q--)
    {
        int op,l,rr;
        cin>>op>>l>>rr;
        if(op==1)
        {
            int p1=lower_bound(r+1,r+n+1,l)-r;
            int p2=upper_bound(r+1,r+n+1,rr)-r;
            cout<<p2-p1<<'\n';
        }
        else
        {
            int p1=lower_bound(c+1,c+n+1,l)-c;
            int p2=upper_bound(c+1,c+n+1,rr)-c;
            cout<<p2-p1<<'\n';
        }
    }
    Hex AK IOI
}
AC 记录

:::info[什么是 lower_bound 和 upper_bound?]

这是 C++ <algorithm> 库里的二分查找函数。

注意:必须用在已经排好序的数组上。

:::

本题解使用了 deepseek-v4.1-flash 进行润色以保证格式的正确。