两列上升序列由若干线段相连,求两两交点的个数。
按a大->小序列排序(主),b序列同上(次),求b序列的正序数对数即可。
树状数组的应用之一:求A数组中前k-1项中比第k项小的元素的个数(数组中元素均正)
拓展应用:求逆序数/正序数对数。在上面基础上求和即可
#include<stdio.h>
#include<iostream>
#include<string.h>
#include<algorithm>
#define maxn 1000100
#define mem(a,b) memset(a,b,sizeof(a))
#define lowbit(x) x&(-x)
#define ll long long
using namespace std;
struct node{
ll e,w;
bool operator<(const node& d) const{
return (e>d.e||(e==d.e&&w>d.w));
}
}coast[maxn];
ll c[1100],ans;
int t,n,m,k;
void update(int i,ll x){
for(;i<=m;i+=lowbit(i)) c[i]+=x;
}
ll sum(int i){
ll s=0;
for(;i>0;i-=lowbit(i)) s+=c[i];
return s;
}
int main(){
//freopen("a.txt","r",stdin);
scanf("%d",&t);
for(int cas=1;cas<=t;cas++){
scanf("%d%d%d",&n,&m,&k);
mem(c,0),ans=0;
for(int i=1;i<=k;i++){
scanf("%lld%lld",&coast[i].e,&coast[i].w);
}
sort(coast+1,coast+k+1);
for(int i=1;i<=k;i++){
ans+=sum(coast[i].w-1);
update(coast[i].w,1);
}
printf("Test case %d: %lld\n",cas,ans);
}
}
bug:数据卡int