题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4325
题意:区间更新单点查询的线段树。
思路:更新和查询的范围都是1e9,所以需要离散一下。查找离散后的值直接lower_bound二分查找。
代码:
#include <bits/stdc++.h>
#define INF 0x3f3f3f3f
#define eps 1e-8
#define fuck(x) cout<<"<"<<x<<">"<<endl
#define fi first
#define se second
#define pb push_back
#define lson l, m, rt<<1
#define rson m+1, r, rt<<1|1
using namespace std;
typedef long long LL;
typedef unsigned long long ull;
typedef pair<LL, LL> pii;
const double PI = acos(-1.0);
const LL INFLL = 0x3f3f3f3f3f3f3f3fll;
const int maxn = 1e5 + 5;
const int mod = 1e9 + 7;
int t;
int n,Q;
int l[maxn],r[maxn],q[maxn];
vector<int>x;
int sum[maxn<<2],lazy[maxn<<2];
void push_up(int rt){
sum[rt]=sum[rt<<1]+sum[rt<<1|1];
}
void push_down(int rt,int m){
if (lazy[rt]){
lazy[rt<<1]+=lazy[rt];
lazy[rt<<1|1]+=lazy[rt];
sum[rt<<1]+=lazy[rt]*(m-(m>>1));
sum[rt<<1|1]+=lazy[rt]*(m>>1);
lazy[rt]=0;
}
}
void build(int l,int r,int rt){
lazy[rt]=0;
if (l==r) {
sum[rt]=0;
return;
}
int m=(l+r)>>1;
build(lson);
build(rson);
push_up(rt);
}
void update(int L,int R,int l,int r,int rt){
if (l>=L&&r<=R){
lazy[rt]++;
sum[rt]+=r-l+1;
return;
}
push_down(rt,r-l+1);
int m=(l+r)>>1;
if (L<=m) update(L,R,lson);
if (R>m) update(L,R,rson);
push_up(rt);
}
int query(int p,int l,int r,int rt){
if (l==r){
return sum[rt];
}
push_down(rt,r-l+1);
int ans=0;
int m=(l+r)>>1;
if (p<=m) ans+=query(p,lson);
else ans+=query(p,rson);
return ans;
}
int k=0;
int main() {
scanf ("%d",&t);
while (t--){
x.clear();
scanf ("%d%d",&n,&Q);
for (int i=0;i<n;i++){
scanf ("%d%d",&l[i],&r[i]);
x.pb(l[i]);
x.pb(r[i]);
}
for (int i=0;i<Q;i++){
scanf ("%d",&q[i]);
x.pb(q[i]);
}
printf ("Case #%d:\n",++k);
sort(x.begin(),x.end());
x.erase(unique(x.begin(),x.end()),x.end());
int sz=x.size();
build(1,sz,1);
for (int i=0;i<n;i++){
int ll=lower_bound(x.begin(),x.end(),l[i])-x.begin();
int rr=lower_bound(x.begin(),x.end(),r[i])-x.begin();
update(ll+1,rr+1,1,sz,1);
}
for (int i=0;i<Q;i++){
int pos=lower_bound(x.begin(),x.end(),q[i])-x.begin();
int ans=query(pos+1,1,sz,1);
printf ("%d\n",ans);
}
}
return 0;
}