求升序或降序三元组的数量
bit求出每个数两侧大于和小于的数的个数,然后枚举三元组中间数字。
code
class Solution {
public:
int c[100050];
int lowbit(int x){
return x&(-x);
}
void add(int i,int x){
int n=int(1e5);
while(i<=n){
c[i]+=x;
i+=lowbit(i);
}
}
int sum(int i){
int ans=0;
int n=int(1e5);
while(i){
ans+=c[i];
i-=lowbit(i);
}
return ans;
}
int numTeams(vector<int>& rating) {
int n=rating.size();
vector<int> les(n,0),rib(n,0),leb(n,0),ris(n,0);
int ans=0;
for(int i=n-1;i>=0;i--){
ris[i]=sum(rating[i]);
rib[i]=(n-1-i)-ris[i];
add(rating[i],1);
}
memset(c,0,sizeof(c));
for(int i=0;i<n;i++){
les[i]=sum(rating[i]);
leb[i]=i-les[i];
add(rating[i],1);
}
for(int i=0;i<n;i++){
ans+=les[i]*rib[i];
ans+=leb[i]*ris[i];
}
return ans;
}
};