给出一些 相连关系,要判断总共有多少相交关系。。
用树状数组求解。。
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define for if(0);else for
#define MAXN 1000050
#define LL __int64
struct In{
int x,y;
}dat[MAXN];
LL c[MAXN];
int N,M,K;
LL cmp(In a,In b){
if(a.x!=b.x)return a.x<b.x;
return a.y>b.y;
}
LL lowbit(int x){
return x&(-x);
}
void update(int i){
while(i<=M+1){
c[i]++;
i+=lowbit(i);
}
}
LL getsum(int i){
LL sum=0;
while(i>0){
sum+=c[i];
i-=lowbit(i);
}
return sum;
}
int main(){
int t;
int cas=0;
scanf("%d",&t);
while(t--){
scanf("%d%d%d",&N,&M,&K);
for(int i=0;i<K;i++){
scanf("%d%d",&dat[i].x,&dat[i].y);
dat[i].x++;
dat[i].y++;
}
sort(dat,dat+K,cmp);//按x从小到大,y从大到小排序
memset(c,0,sizeof(c));
LL cnt=0;//这里要用 __int64
int pre=0;
update(dat[0].y);
//printf("%d\n",c[5]);
//printf("%d\n",getsum(dat[0].y));
for(int i=1;i<K;i++){
if(dat[i-1].x==dat[i].x)pre++;//如果x相同,则cnt值要减去pre,因为端点相同不算cross
else pre=0;
cnt+=getsum(M+1)-getsum(dat[i].y)-pre;
update(dat[i].y);
//printf("%d\n",pre);
}
printf("Test case %d: ",++cas);//坑爹啊,这句忘了,送了数次 wa
printf("%I64d\n",cnt);
}
}
/*
3 4 7
1 4
2 4
2 3
3 1
3 2
3 3
3 4
answer: 9
*/