bzoj3295: [Cqoi2011]动态逆序对 cdq分治
https://www.lydsy.com/JudgeOnline/problem.php?id=3295
把删除看成反向插入,把时间看成一维,下标看成一维,值看成一维,就变成了三维偏序问题了,需要正着扫一遍和反着扫一遍
/**************************************************************
Problem: 3295
User: walfy
Language: C++
Result: Accepted
Time:2476 ms
Memory:4032 kb
****************************************************************/
//#pragma comment(linker, "/stack:200000000")
//#pragma GCC optimize("Ofast,no-stack-protector")
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
//#pragma GCC optimize("unroll-loops")
#include<bits/stdc++.h>
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define pi acos(-1.0)
#define ll long long
#define vi vector<int>
#define mod 1000000007
#define ld long double
#define C 0.5772156649
#define ls l,m,rt<<1
#define rs m+1,r,rt<<1|1
#define pil pair<int,ll>
#define pli pair<ll,int>
#define pii pair<int,int>
#define cd complex<double>
#define ull unsigned long long
#define base 1000000000000000000
#define fio ios::sync_with_stdio(false);cin.tie(0)
using namespace std;
const double eps=1e-6;
const int N=100000+10,maxn=300000+10,inf=0x3f3f3f3f,INF=0x3f3f3f3f3f3f3f3f;
int id[N];
struct node{
int a,b,c;
ll ans;
bool operator <(const node &rhs)const
{
return a<rhs.a||a==rhs.a&&b<rhs.b||a==rhs.a&&b==rhs.b&&c<rhs.c;
}
}p[N];
struct bit{
int sum[N];
void update(int i,int v)
{
for(;i<N;i+=i&(-i))sum[i]+=v;
}
int query(int i)
{
int ans=0;
for(;i;i-=i&(-i))ans+=sum[i];
return ans;
}
}b;
bool cmp1(const node &x,const node &y){return x.c<y.c;}
void cdq(int l,int r)
{
if(l==r)return ;
int m=(l+r)>>1;
cdq(l,m);cdq(m+1,r);
sort(p+l,p+m+1,cmp1);sort(p+m+1,p+r+1,cmp1);
int le=l,ri=m+1;
while(ri<=r)
{
if(le<=m&&p[le].c<p[ri].c)b.update(p[le].b,1),le++;
else
{
p[ri].ans+=b.query(N-1)-b.query(p[ri].b);
// printf("%d+++++\n",b.query(p[ri].b));
// if(b.query(N-1)-b.query(p[ri].b)>0)printf("#######%d %d %d %d\n",p[ri].a,p[ri].b,p[ri].c,p[ri].ans);
ri++;
}
}
for(int i=l;i<le;i++)b.update(p[i].b,-1);
le=m,ri=r;
while(ri>=m+1)
{
if(le>=l&&p[le].c>p[ri].c)b.update(p[le].b,1),le--;
else
{
p[ri].ans+=b.query(p[ri].b);
// printf("%d+++++\n",b.query(p[ri].b));
// if(b.query(N-1)-b.query(p[ri].b)>0)printf("#######%d %d %d %d\n",p[ri].a,p[ri].b,p[ri].c,p[ri].ans);
ri--;
}
}
for(int i=m;i>le;i--)b.update(p[i].b,-1);
// for(int i=l;i<=m;i++)printf("le: %d %d %d\n",p[i].a,p[i].b,p[i].c);
// for(int i=m+1;i<=r;i++)printf("ri: %d %d %d\n",p[i].a,p[i].b,p[i].c);
// puts("--------------");
}
int main()
{
int n,m;
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
{
scanf("%d",&p[i].b);p[i].c=i;
id[p[i].b]=i;
}
for(int i=m;i>=1;i--)
{
int x;scanf("%d",&x);
p[id[x]].a=i;
}
sort(p+1,p+1+n);
cdq(1,n);
sort(p+1,p+1+n);
for(int i=1;i<=n;i++)
p[i].ans+=p[i-1].ans;
for(int i=n;i>=1;i--)
if(p[i].a)
printf("%lld\n",p[i].ans);
return 0;
}
/********************
5 4
1 5 3 4 2
5 1 4 2
********************/