table of Contents
1. Title
Given three integer arrays
A=[A1,A2,…AN],
B=[B1,B2,…BN],
C=[C1,C2,…CN],
Please count how many triples (i,j,k) satisfy:
1≤i,j,k≤N
Ai<Bj<Ck
input format The
first line contains an integer N.
The second line contains N integers A1, A2,...AN.
The third line contains N integers B1, B2,...BN.
The fourth line contains N integers C1, C2,...CN.
Output format
An integer represents the answer.
Data range
1≤N≤105,
0≤Ai,Bi,Ci≤105
Input example:
3
1 1 1
2 2 2
3 3 3
Output example:
27
2. Thinking
Idea: Binary first sorts the three arrays, then traverses the b array, for each number b[i] in b, find the last subscript of the number less than b[i] in the a array, here we record it as l. Find the first subscript of a number greater than b[i] in the c array, here we mark it as r. In the a array, the number of numbers less than b[i] is l+1, and in the c array, the number of numbers greater than b[i] is nr. Therefore, when in the triple increment group, the number with b[i] as the middle number is (l+1)*(nr). Traverse the b array, accumulation is the answer.
3. Code
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long LL;
const int N=1e5+10;
int a[N],b[N],c[N];
int main()
{
int n;
scanf("%d",&n);
for(int i=0;i<n;i++) scanf("%d",&a[i]);
for(int i=0;i<n;i++) scanf("%d",&b[i]);
for(int i=0;i<n;i++) scanf("%d",&c[i]);
sort(a,a+n); //二分需要满足单调性
sort(b,b+n);
sort(c,c+n);
LL res=0; //答案可能会很大
for(int i=0;i<n;i++)
{
int l=0,r=n-1; //二分查找a数组中最后一个小于b[i]的数的下标
while(l<r)
{
int mid=(l+r+1)/2;
if(a[mid]<b[i]) l=mid;
else r=mid-1;
}
if(a[l]>=b[i]) //如果未找到小于b[i]的数,将x标记为-1,后续计算时 x+1==0
{
l=-1;
}
int x=l;
l=0,r=n-1;
while(l<r)
{
int mid=(l+r)/2;
if(c[mid]>b[i]) r=mid;
else l=mid+1;
}
if(c[l]<=b[i]) //如果未找到大于b[i]的数,将y标记为n,后续计算时 n-y==0;
{
r=n;
}
int y=r;
res+=(LL)(x+1)*(n-y);
}
printf("%lld\n",res);
return 0;
}