N ladies attend the ball in the King's palace. Every lady can be described with three values: beauty, intellect and richness. King's Master of Ceremonies knows that ladies are very special creatures. If some lady understands that there is other lady at the ball which is more beautiful, smarter and more rich, she can jump out of the window. He knows values of all ladies and wants to find out how many probable self-murderers will be on the ball. Lets denote beauty of the i-th lady by Bi, her intellect by Ii and her richness by Ri. Then i-th lady is a probable self-murderer if there is some j-th lady that Bi < Bj, Ii < Ij, Ri < Rj. Find the number of probable self-murderers.
The first line contains one integer N (1 ≤ N ≤ 500000). The second line contains N integer numbers Bi, separated by single spaces. The third and the fourth lines contain sequences Ii and Ri in the same format. It is guaranteed that 0 ≤ Bi, Ii, Ri ≤ 109.
Output the answer to the problem.
3 1 4 2 4 3 2 2 5 3
1
题意:
给定n个三元组(B,L,R),求有多少个三元组(B[i],L[i],R[i]),存在(B[j],L[j],R[j])使得B[i]<B[j] && L[i]<L[j] && R[I]<R[j].
分析:
对每一维离散化,然后按第一维从大到小,第二维从小到大,第三维从大到小的顺序对这些三元组进行排序,建立一棵线段树,维护第二维取值对应第三维的最大值,每一次枚举时先查询区间[L[i]+1,n]的最大值k,如果k>R[i]则ans++,并更新线段树上L[i]处的值。注意到按前述方法排序之后依次枚举时保证第一维是不减的,且在第一维相同时第二维递增,保证先插入线段树的值不会对当前询问产生影响。复杂度O(nlogn)。
代码:
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<iostream>
#include<algorithm>
using namespace std;
const int MAXN=500005;
int b[MAXN],l[MAXN],r[MAXN],t[MAXN];
void modify(int s[],int h[],int n)
{
for(int i=1;i<=n;i++)h[i]=s[i];
sort(h+1,h+n+1);
int cnt=unique(h+1,h+n+1)-(h+1);
for(int i=1;i<=n;i++)
s[i]=lower_bound(h+1,h+cnt+1,s[i])-h;
}
struct person
{
int b,l,r;
person(int b=0,int l=0,int r=0):b(b),l(l),r(r){}
bool operator < (const person &q)const
{
return b==q.b ? (l==q.l ? r>q.r : l<q.l) : b>q.b;
}
}p[MAXN];
struct node
{
int l,r,m,v;
}s[MAXN<<2];
void push_up(int num)
{
s[num].v=max(s[num<<1].v,s[num<<1|1].v);
}
void build(int l,int r,int num)
{
int m=(l+r)>>1;
s[num].l=l;
s[num].r=r;
s[num].m=m;
if(r-l==1)s[num].v=0;
else
{
build(l,m,num<<1);
build(m,r,num<<1|1);
push_up(num);
}
}
void update(int p,int k,int num)
{
if(s[num].l==p && s[num].r==p+1)
{
s[num].v=max(s[num].v,k);
return;
}
if(p<s[num].m)update(p,k,num<<1);
else update(p,k,num<<1|1);
push_up(num);
}
int query(int l,int r,int num)
{
if(s[num].l==l && s[num].r==r)return s[num].v;
if(r<=s[num].m)return query(l,r,num<<1);
if(l>=s[num].m)return query(l,r,num<<1|1);
return max(query(l,s[num].m,num<<1),query(s[num].m,r,num<<1|1));
}
int main()
{
int n;
scanf("%d",&n);
for(int i=1;i<=n;i++)scanf("%d",&b[i]);
for(int i=1;i<=n;i++)scanf("%d",&l[i]);
for(int i=1;i<=n;i++)scanf("%d",&r[i]);
modify(b,t,n);
modify(l,t,n);
modify(r,t,n);
for(int i=1;i<=n;i++)
{
p[i]=person(b[i],l[i],r[i]);
}
sort(p+1,p+n+1);
build(1,n+2,1);
int ans=0;
for(int i=1;i<=n;i++)
{
if(query(p[i].l+1,n+2,1)>p[i].r)ans++;
update(p[i].l,p[i].r,1);
}
printf("%d\n",ans);
return 0;
}