链接:http://acm.hdu.edu.cn/showproblem.php?pid=5792
题意:给你一个序列Ai,让你找出有多少个一个四元组(a<b.c<d)使得Aa<Ab,Ac>Ad.
分析:先离散化,然后用树状数组统计每个数前后有多少小于大于它的数,这个时候我们先不考虑重复的算出ans,然后用ans减去a=c,c=d,b=d,b=c的。
四个for枚举就好了。
a==c ans-=BGreaterNum[i]*BLessNum[i];
b==d ans-=FGreaterNum[i]*FLessNum[i];
a==d ans-=BGreaterNum[i]*FGreaterNum[i];
b==c ans-=FLessNum[i]*BLessNum[i];
代码:
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<string>
#include<vector>
#include<queue>
#include<cmath>
#include<stack>
#include<set>
#include<map>
#define INF 0x3f3f3f3f
#define Mn 50005
#define Mm 2000005
#define mod 1000000007
#define CLR(a,b) memset((a),(b),sizeof((a)))
#define CLRS(a,b,Size) memset((a),(b),sizeof((a[0]))*(Size+1))
#define CPY(a,b) memcpy ((a), (b), sizeof((a)))
#pragma comment(linker, "/STACK:102400000,102400000")
#define ul u<<1
#define ur (u<<1)|1
using namespace std;
typedef long long ll;
ll bit[Mn];
int lowbit(int x) {return x&(-x);}
int N;
void push(int x,int val) {
while(x<=N) {
bit[x]+=val;
x+=lowbit(x);
}
}
ll getNum(int x) {
ll re=0;
while(x>0) {
re+=bit[x];
x-=lowbit(x);
}
return re;
}
int a[Mn],b[Mn];
ll FLessNum[Mn],FGreaterNum[Mn];
ll BLessNum[Mn],BGreaterNum[Mn];
int main() {
int n;
while(~scanf("%d",&n)) {
N=n;
CLR(bit,0);
for(int i=0;i<n;i++) {
scanf("%d",&a[i]);
b[i]=a[i];
}
sort(b,b+n);
int cnt=unique(b,b+n)-b;
for(int i=0;i<n;i++) a[i]=lower_bound(b,b+cnt,a[i])-b+1;
for(int i=0;i<n;i++) {
FLessNum[i]=getNum(a[i]-1);
FGreaterNum[i]=getNum(n)-getNum(a[i]);
push(a[i],1);
}
CLR(bit,0);
ll sum1=0,sum2=0,ans=0;
for(int i=n-1;i>=0;i--) {
BLessNum[i]=getNum(a[i]-1);
BGreaterNum[i]=getNum(n)-getNum(a[i]);
sum1+=BLessNum[i];
sum2+=BGreaterNum[i];
push(a[i],1);
}
ans=sum1*sum2;
for(int i=0;i<n;i++) {///a==c
ans-=BGreaterNum[i]*BLessNum[i];
}
for(int i=0;i<n;i++) {///b==d
ans-=FGreaterNum[i]*FLessNum[i];
}
for(int i=0;i<n;i++){///a==d
ans-=BGreaterNum[i]*FGreaterNum[i];
}
for(int i=0;i<n;i++) {///b==c
ans-=FLessNum[i]*BLessNum[i];
}
printf("%I64d\n",ans);
}
return 0;
}