这题是学习cdq分治经测试的第一题,之前还有一道cdq分治和树状数组结合作为我学习的第一题,看了很久才看明白但是oj上没那题了。这个代码是抄别人的..感受到领悟了思想和会自己写出来还是两回事... 代码来源博客:http://blog.csdn.net/kg20006/article/details/51317244
#include <bits/stdc++.h>
using namespace std;
const int maxn=100005;
int ans[maxn];
struct op
{
int tp,t,x,id;
op(){}
op(int a, int b, int c, int d) { tp = a, t = b, x = c, id = d; }
bool operator < (const op& a) const{ return t < a.t; }
}qry[maxn];
map<int,int> mp;
bool cmp(op a,op b)
{
return a.id<b.id;
}
void cdq(int l,int r)
{
int i;
if(l==r) return;
int mid=(l+r)>>1;
cdq(l,mid);
cdq(mid+1,r);
sort(qry+l,qry+r+1);// sort这个函数,左边加的是下标,右边加的是下标加一
for(i=l;i<=r;i++)
{
op &x=qry[i];
if(x.id<=mid)
{
if(x.tp==1) mp[x.x]++;
else if(x.tp==2) mp[x.x]--;
}
else
if(x.tp==3) ans[x.id]+=mp[x.x];
}
for(i=l;i<=r;i++)
{
op &x=qry[i];
if(x.id<=mid)
{
if(x.tp==1) mp[x.x]--;
else if(x.tp==2) mp[x.x]++;
}
}
sort(qry+l,qry+r+1,cmp);
}
int main()
{
int n,i;
scanf("%d",&n);
for(i=1;i<=n;i++)
{
scanf("%d%d%d",&qry[i].tp,&qry[i].t,&qry[i].x);
qry[i].id=i;
}
cdq(1,n);
for(i=1;i<=n;i++)
if(qry[i].tp==3) printf("%d\n",ans[i]);
}