题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3465
题目大意:求交点的x坐标落于开区间(l,r)的直线对对数.
思路:设直线和x=l交于(l,h1),和x=r交于(r,h2),按照h1降序排序(h1相等的按照h2降序).得到一个h2数列,求这个h2数列的顺序数(i<j && h2[i]<h2[j]),可以用线段树或树状数组.
代码:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include <math.h>
#include <time.h>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
#define ull unsigned __int64
#define ll __int64
//#define ull unsigned long long
//#define ll long long
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define middle (l+r)>>1
#define MOD 1000000007
#define esp (1e-4)
const int INF=0x3F3F3F3F;
const double DINF=10001.00;
//const double pi=acos(-1.0);
const int N=50010;
int n,m;
int sum[N];
double hash[N],L,R;
struct node{
double h1,h2;
bool operator < (const node& p) const {
if(h1==p.h1) return h2 > p.h2;
return h1 > p.h1;
}
}a[N];
int lowbit(int x){return x&(-x);}
void Add(int pos,int c){
while(pos<=m+1) sum[pos]+=c,pos+=lowbit(pos);
}
int Sum(int pos){
int r=0;
while(pos>0) r+=sum[pos],pos-=lowbit(pos);
return r;
}
int bs(double key,int size,double A[]){
int l=0,r=size-1,mid;
while(l<=r){
mid=middle;
if(key==A[mid]) return mid;
else if(key>A[mid]) l=mid+1;
else if(key<A[mid]) r=mid-1;
}
return -1;
}
int main(){
//freopen("1.in","r",stdin);
//freopen("1.out","w",stdout);
int i,j,k,pos,ret;
//int T,cas;scanf("%d",&T);for(cas=1;cas<=T;cas++)
while(~scanf("%d",&n)){
scanf("%lf%lf",&L,&R);
for(i=j=k=0;i<n;i++){
double x1,y1,x2,y2;
scanf("%lf%lf%lf%lf",&x1,&y1,&x2,&y2);
if(x1==x2){
if(L<x1 && x1<R) k++;
}else{
a[j].h1=(L-x1)*(y1-y2)/(x1-x2)+y1;
hash[j]=a[j].h2=(R-x1)*(y1-y2)/(x1-x2)+y1;
j++;
}
}
sort(hash,hash+j);
for(i=m=1;i<j;i++) if(hash[i]!=hash[i-1]) hash[m++]=hash[i];
sort(a,a+j);
memset(sum,0,sizeof(sum));
for(i=ret=0;i<j;i++){
pos=bs(a[i].h2,m,hash);
ret+=Sum(pos);
Add(pos+1,1);
}
printf("%d\n",ret+k*j);
}
return 0;
}