[ABC482C] Band Count
main idea
题目大意
给定一个 的网格,上面有 个棋子,第 个棋子坐标为 。
有 次查询,每次为以下两种之一:
1 u d:求第 行到第 行内的棋子总数。2 l r:求第 列到第 列内的棋子总数。
输出每次查询的棋子数。
Solutions
做法
容易想到的暴力做法是开一个二维数组 进行遍历或前缀和统计,但 的数据范围,显然会 MLE(甚至 TLE)。
但我们敏锐地注意到,每次查询的行和列是相互独立、互不干扰的。并且棋子的总数仅有 ,这意味着我们只需要用两个一维数组分别存下所有棋子所在的行号与列号并排序。对于每次查询,通过二分查找(lower_bound 和 upper_bound)锁定区间的左右端点,相减即可得到区间内的棋子个数。
时间复杂度 ,空间复杂度 。
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
}什么是 lower_bound 和 upper_bound?
这是 C++ <algorithm> 库里的二分查找函数。
注意:必须用在已经排好序的数组上。
lower_bound(起始, 结束, x):返回第一个 大于等于 的元素位置(下界)。upper_bound(起始, 结束, x):返回第一个 严格大于 的元素位置(上界)。
本题解使用了 deepseek-v4.1-flash 进行润色以保证格式的正确。